iterator's behavior when container's size is zero.

#include <stdlib.h>
#include <iostream>
#include <map>
main() {
std::map<size_t,int> mt;
std::map< size_t, int>::iterator iter;
iter = mt.begin();
std::cout << "begin --" << iter->first <<" -- " << iter->second<< std::endl;
iter = mt.end();
std::cout << "end --" << iter->first <<" -- " << iter->second<< std::endl;
iter = iter++;
std::cout << "++ --" << iter->first <<" -- " << iter->second<< std::endl;
}


In this program, I want to understand the following issues.
(i) how should iter->first or iter->second behave when the container size is zero. Is it risky , is it defined, undefined.
(ii) On linux machine, I see a hang in the second last line
i.e. iter = iter++ , Any idea why....??

Thanks
Ashish
When the container is empty begin() == end(). You should never dereference the iterator returned by end(). It should only be used to compare with other iterators to know that you have reached the end. What you are doing is undefined.
dereferencing end() is undefined.

iter = end()
iter++
--- Here is this dereferencing. But it hangs in this iter++ statement.
--- Any particular reason for this hang.

Regarding the begin() -- is there any thing undefined for begin() too if the size of the container is ZERO.
If the size is zero both begin() and end() return the same iterator so you can't dereference any of them.

1
2
iter = end()
iter++
I think this is undefined. You can't go past the end iterator.

You should use something like:
1
2
3
4
5
6
iter = mt.begin();

if(iter != mt.end())
{
    std::cout << "begin --" << iter->first <<" -- " << iter->second<< std::endl;
}
Topic archived. No new replies allowed.