Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I need to initialize an interator by zero value. I tried following code

#include <map>
std::map<int, int>::iterator foo() {
    std::map<int, int>::iterator ret;
    ret = std::map<int, int>::iterator(0);
    return ret;
}

It successfully compiled by gcc and intel C++ compilers on Linux. Also, this compiled well in minGW on Windows. The code provided with -O2 is

xorl eax, eax
ret

The issue is compilation under VisualStudio. The error is: error C2440: '' : cannot convert from 'int' to 'std::_Tree_iterator>>> No constructor could take the source type, or constructor overload resolution was ambiguous.

Could you please give me an idea how to cast zero or rephrase initialization of iterator?

Thank you

PS

main idea is getting NULL at the end of the "list"

(it = a.begin(); it != a.end(); it = it->next)

that based on map::iterators from diffrent map objects.

a::end() {
    return std::map<K, V>::iterator(0)
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
410 views
Welcome To Ask or Share your Answers For Others

1 Answer

No, you don't.

You need to initialize either with past-the-end value (which you can only get from the container it is supposed to iterate):

return map.end();

or at worst with default value:

return std::map<int, int>::iterator();

The difference is that the former can be tested whether it is end iterator, while the later is basically untouchable. If you do the later, you basically have to remember not to touch it. You can't even compare default-constructed iterators for equality to check that they are default-constructed (most implementations define the comparison, but some may not).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...