- Code: Select all
#include <iostream>
#include <string>
#include <unordered_map>
int main()
{
// TR1 unordered_map Example, An unordered_map is exactly that
// an STL container that is unordered
// Create our map, The key will be an integer value and each key will hold a string value
typedef std::tr1::unordered_map<int, std::string> NewMap;
NewMap TestMap;
// Let's add some data, Method 1
TestMap.insert(std::pair<int, std::string>(0, "Hello"));
// More Data, Method 2
TestMap[1] = "World";
// Let's print out the map
for (NewMap::const_iterator It = TestMap.begin(); It != TestMap.end(); ++It)
{
// Print both the key and the value of that key
// First = Key (Int), Second = Value of that key (String)
std::cout << (*It).first << " equals " << (*It).second << std::endl;
}
return 0;
}
Output:
- Code: Select all
0 equals Hello
1 equals World
Press any key to continue . . .
It's pretty much self explanatory code, It works like any other container you know (Vector etc.) just it has a key with a corresponding value - You can expand on the value by using a struct, so each key could have multiple values/variables.
You could also have the key as a string and then retrieve data that you need by a name rather than looping thru each member until you find the one you want making life easier.
