std::map

A C++ container type called std::map is used to store elements that are formed by a combination of key value and mapped value. How do you iterate through this container and find the value mapped to a specific key?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
std::map<std::string,std::string> x;
x["test"] = "a";
x["2"] = "c";

// Enumerate all keys/values
for(auto it : x)
{
    std::cout << it->first << " : " << it->second << std::endl;
}

// Find a specific key
auto it = x.find("test");
if(it != x.end())
    std::cout << it->second << std::endl;

// Print an element (Element will be added if not present)
std::cout << x["2"];
Last edited on
You would iterate through it using its iterators and access members using the [] operator. You can also use the find method to check if an key is within the map. For more info please goto http://www.cplusplus.com/reference/map/map/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <map>

int main() {
	std::map<std::string, int> myMap;
	myMap["One"]=1;
	myMap["Two"]=2;
	myMap["Three"]=3;
	
	//iteration
	for(std::map<std::string, int>::iterator it=myMap.begin(); it!=myMap.end(); ++it) { 
		std::cout<<(*it).first<<' '<<(*it).second<<'\n';
	}
	
	
	//Accessing members using []
	std::cout<<myMap["Three"]<<'\n'
		 <<myMap["Four"]<<'\n'; //Outputs Adds the key value pair {"Four", 0}
	
	//Findign a key	 
	std::map<std::string, int>::iterator find_four=myMap.find("Four");
	std::cout<<"A four does"<<(find_four==myMap.end() ? " not" : " ")<<"exist in myMap"<<'\n';
	
	return(0);
}


Did not see your post when I posted. Sorry EssGeEich.
Last edited on
That's okay Script Coder, yours is in C++03 :D
Topic archived. No new replies allowed.