Created
November 9, 2016 02:57
-
-
Save tansey/359b59592f405e99a850f0daa0025bfd to your computer and use it in GitHub Desktop.
terrible STL set iterator behavior
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <set> | |
#include <iostream> | |
class A | |
{ | |
std::set<int> s; | |
public: | |
A() { s.insert(0); s.insert(1); } | |
std::set<int> getSet() { return s; } | |
}; | |
int main(void) | |
{ | |
A a; | |
std::cout << "A contains " << a.getSet().size() << " elements. They are listed below:" << std::endl; | |
for (std::set<int>::const_iterator it = a.getSet().begin(); it != a.getSet().end(); ++it){ | |
std::cout << *it << std::endl; | |
} | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Expected output:
Actual output:
The issue seems to be that I'm returning a set by value. However, that is the recommended style since STL containers are shallow copied. In the case of set, it seems that it causes weird behavior.