Why can’t I access elements with operator[] in a const std::map?

at() is a new method for std::map in C++11. Rather than insert a new default constructed element as operator[] does if an element with the given key does not exist, it throws a std::out_of_range exception. (This is similar to the behaviour of at() for deque and vector.) Because of this behaviour it makes sense for … Read more

How do I merge two maps in STL and apply a function for conflicts?

I don’t know of any existing function for that, but you can roll your own from something similar to std::merge implementation to have linear complexity: template<class Map, class Merger> void merge(Map& dest, const Map& source, Merger merger) { auto it1 = dest.begin(); auto it2 = source.begin(); auto&& comp = dest.value_comp(); for (; it1 != dest.end() … Read more

Partial match for the key of a std::map

You can’t efficiently search for substring, but you can for prefix: #include <iostream> #include <map> #include <string> #include <algorithm> using namespace std; typedef map<string, string> TStrStrMap; typedef pair<string, string> TStrStrPair; TStrStrMap::const_iterator FindPrefix(const TStrStrMap& map, const string& search_for) { TStrStrMap::const_iterator i = map.lower_bound(search_for); if (i != map.end()) { const string& key = i->first; if (key.compare(0, search_for.size(), … Read more

C++ std::map items in descending order of keys

Use a custom comparator when the default order doesn’t do it for you. You pass it as the third template parameter ( that’s normally defaulted to std::less<KeyType> ). In your case, you can use std::greater: std::map<int, int, std::greater<int> > m; Example code: #include <map> #include <iostream> #include <functional> int main() { std::map<int, int, std::greater<int>> m … Read more