It seems that I can sort a std::vector<std::pair<int, std::string>>
, and it will sort based on the int value. Is this a well defined thing to do?
Does std::pair
have a default ordering based on its elements?
The pairs in a set are stored in sorted order, sorted by the key i.e. the first value of the pair.
C++ pair is a type that is specified under the utility> header and is used to connect two pair values. The pair's values can be of separate or identical types. To view the values in a pair independently, the class has the member functions first() and second().
std::pair is a class template that provides a way to store two heterogeneous objects as a single unit. A pair is a specific case of a std::tuple with two elements.
std::pair is a struct, the standard says the compiler determines the layout though the order must be maintained, so in the instance of std::pair<char,char> your compiler may decide to place 3-byte padding after each char for optimal alignment, so no you can't assume contiguous memory layout - end of story.
std::pair
uses lexicographic comparison: It will compare based on the first element. If the values of the first elements are equal, it will then compare based on the second element.
The definition in the C++03 standard (section 20.2.2) is:
template <class T1, class T2> bool operator<(const pair<T1, T2>& x, const pair<T1, T2>& y); Returns: x.first < y.first || (!(y.first < x.first) && x.second < y.second).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With