C++ STL Map Stuff
begin() – Returns an iterator to the first element in the map
end() – Returns an iterator to the theoretical element that follows last element in the map
size() – Returns the number of elements in the map
max_size() – Returns the maximum number of elements that the map can hold
empty() – Returns whether the map is empty
pair insert(keyvalue, mapvalue) – Adds a new element to the map
erase(iterator position) – Removes the element at the position pointed by the iterator
erase(const g)– Removes the key value ‘g’ from the map
clear() – Removes all the elements from the map
std::map<int, int> m;
m.insert(pair<int, int>(1,2));
m.insert(pair<int, int>(3,5));
// OR we can use an initializer list
m.insert({1,2})
//remove all elements upto element with key=3
m.erase(m.begin(), m.find(3));
//remove all elements with key=4;
m.erase(4);
//iterate through map
std::map<int, int>::iterator it;
for(it = m.begin();i!=m.end(); ++itr){
std::cout<< it->first << it->second << '\n';
}
std::map<int,int>::iterator
it can be replaced withauto
-
Finding an element in a map
if(m.find(2) != m.end()){ // do something }
m.find(val)
returns an iterator to the position of the element. If element is not found, the returned iterator will be equal to the end of the container
Unordered Map
-
Insert into
unordered_map
unordered_map<int, int> m; m[1] = 10; m[2] = 20;