catalystgma's blog

By catalystgma, 5 years ago, In English

Hi,

I am facing a weird issue when trying to solve a problem, and I have replicated it here: http://cpp.sh/46vyc. I have a map (map<long long, bool>) and I try to iterate through pairs of consecutive indices from it. I print the pair after adding 1 to the first value, and subtracting 1 from the second value.

The output I get looks like:

bruh 3 2

bruh 4 4

....

However, when I uncomment the two lines at the end: http://cpp.sh/3auk3, which do not modify the contents of the map:

while (hh[itv.first] == 1) itv.first++;

while (hh[itv.second] == 1) itv.second--;

The output is now:

bruh 3 2

bruh 4 3

....

Why did the second line change from "4 4" to "4 3"? After all, I didn't modify the contents of the map, and I haven't altered the iterators. I'm not well informed about STL, so please help me.

Thanks!

  • Vote: I like it
  • +4
  • Vote: I do not like it

»
5 years ago, # |
Rev. 2   Vote: I like it +4 Vote: I do not like it

This is because if there is no key for what you are searching map creates a new key .
Change your while loop like this and it should work .

while (hh.find(itv.first)!=hh.end() && hh[itv.first] == 1) itv.first++;

while (hh.find(itv.second)!= hh.end() && hh[itv.second] == 1) itv.second--;

Edit : Like here you were searching for hh[itv.first] and if itv.first doesn't exist in the map , then a new key will be created by map . But if you use map.find(key) then map will not create a new key .

  • »
    »
    5 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Ooh, I didn't think a new key could be added any time I'd query for something in the map. Wow, thanks a lot