Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
421 views
in Technique[技术] by (71.8m points)

std::map iterator initialization by zero in C++

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

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

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...