Created
September 16, 2014 17:01
-
-
Save eraserhd/5af749e021b6d0ae32b0 to your computer and use it in GitHub Desktop.
Iterating through a map.
This file contains hidden or 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 <map> | |
| #include <iostream> | |
| #include <string> | |
| using namespace std; | |
| int main() { | |
| // A map | |
| map<string, int> a_map; | |
| // Put some things in it. | |
| a_map["foo"] = 42; | |
| a_map["baz"] = -1; | |
| a_map["quux"] = 79; | |
| // Iterator over it | |
| for (map<string, int>::const_iterator i = a_map.begin(); // initial state of loop | |
| i != a_map.end(); // check for end of loop | |
| ++i) // advance | |
| { | |
| cout << "found an entry:" << endl; | |
| // I think i->first and i->second are equivalent to (*i).first and | |
| // (*i).second ... Perhaps there was a reason not to do that a long | |
| // time ago, or perhaps my brain is just old. | |
| cout << " key: " << (*i).first << endl; | |
| cout << " value: " << (*i).second << endl; | |
| } | |
| return 0; | |
| } | |
| // Line 16 looks better depending on how modern your C++ compiler is. With C++11, it could be | |
| // for (auto i = a_map.begin(); ... | |
| // | |
| // With GNU C++ before C++11, you could do this: | |
| // | |
| // for (typedecl(a.map.begin()) i = a_map.begin(); ... | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment