Using a std::map<int, ...> how can I ensure at inserting time that iterating over it will take place in ascending order of the integer key?
Using a std::map<int, …> how can I ensure at inserting time that iterating over
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You don’t have to do anything. The map will be in ascending order according to the values of the key.
Internally, the map performs a comparison between keys to order its elements. By default, it uses
std::less<KEY>, which is equivalent tobool operator<(int, int)for integers. For user defined types, you have to options:Implement a
bool operator<(const MyType&, const MyType&)implementing a strict weak ordering comparison between your user defined types. Use this if your type has a natural orderingProvide a binary functor that implements strict weak ordering, which you can pass as the 3rd template parameter to the map. Use this if your type does not have a natural ordering, or if you want to build the map with an ordering different to that used by
std::less<Key>via thebool operator<(...)from point 1.What typically happens behind the scenes is that the map is implemented as a self-balancing binary tree, and the strict weak ordering is used to place new elements in the map, and to determine whether two elements are equal. As an aside, the same logic applies to
std::set, where the key and value are one and the same.