scubnoob
scubnoob

Reputation: 7

Iterator confusion using maps

sorry because this question isn't really advanced, but I am having lots of trouble understanding why this program works the way it does.

#include <iostream>
#include <fstream>
#include <set>
#include <vector>
#include <map>

using namespace std;

int main() {
    ofstream fout("castle.out");
    ifstream fin("castle.in");
    map<int, int, greater<int> > cnt;
    map<int, int, greater<int> >::iterator x;
    x = cnt.begin();
    cnt[1] = 0;
    cnt[2] = 7;
    fout << x->first; //This outputs 2
    x++;
    fout << x->second;//This outputs 2 again, why not 0?

    return 0;
}

So I defined a map called cnt, and then made an iterator for it x. I ordered it by greatest integer to least greatest integer. I set that iterator equal to x.begin(), and then I outputted the value of x, using first. But then I wanted to output the value 0, so I did one x++; and then tried to output the value of x->first. The idea behind this was that the iterator would increase by one and point to the next pair in my map, so then it would point to 1, which comes after the 2.

Why does it not work and give me 2 again?

I realized that if I do this instead:

x++;
x++:
fout << x-> first;

with two x++, I will have the value 1. Why is this? Thanks!

Upvotes: 0

Views: 40

Answers (1)

NathanOliver
NathanOliver

Reputation: 180630

Your code has undefined behavior.

x = cnt.begin();

Sets x to begin() while the container is empty which effectively gives you the end() iterator. Since std::map::operartor[] doesn't invalidate any iterators you still have an end() iterator and dereferencing it is undefined behavior.

Upvotes: 2

Related Questions