View on GitHub

CC

CC practice and cheat sheets

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 with auto

Unordered Map