samedi 19 avril 2014

c ++ - C ++ 11 : map::lower_bound ne fonctionne pas correctement pour les éléments 2 ou moins sous Linux - Stack Overflow


If I run following C++11 example in Linux (Debian 7, GCC 4.8.2, Eclipse CDT), the while cycle is infinite. First loop is correct. Iterator is decremented by 1 and it references to the first map element. But second and other loops are incorrect. Decrement operator doesn't decrement iterator. It still references to the first element. If I remove comment (in map initialization), while cycle will stop. Could you please tell me, what I did wrong? Thank you very much for every comment.


#include <iostream>
#include <map>
using namespace std;

int main() {
std::map<int, int> mymap = {{1, 100}, {2, 200}/*, {3, 300}*/};
auto it = mymap.lower_bound(2);
cout << "mymap key: " << it->first << endl;
while(--it != buff.end())
cout << "mymap key: " << it->first << endl;

return 0;
}

Note: This code works correct under Windows platform (Visual studio 2013 Express).




You pass a begin() iterator to this line:


while(--it != buff.end())

And --begin() yields undefined behaviour.



If I run following C++11 example in Linux (Debian 7, GCC 4.8.2, Eclipse CDT), the while cycle is infinite. First loop is correct. Iterator is decremented by 1 and it references to the first map element. But second and other loops are incorrect. Decrement operator doesn't decrement iterator. It still references to the first element. If I remove comment (in map initialization), while cycle will stop. Could you please tell me, what I did wrong? Thank you very much for every comment.


#include <iostream>
#include <map>
using namespace std;

int main() {
std::map<int, int> mymap = {{1, 100}, {2, 200}/*, {3, 300}*/};
auto it = mymap.lower_bound(2);
cout << "mymap key: " << it->first << endl;
while(--it != buff.end())
cout << "mymap key: " << it->first << endl;

return 0;
}

Note: This code works correct under Windows platform (Visual studio 2013 Express).



You pass a begin() iterator to this line:


while(--it != buff.end())

And --begin() yields undefined behaviour.


0 commentaires:

Enregistrer un commentaire