Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is std::pair<int, std::string> ordering well-defined?

Tags:

c++

sorting

stl

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?

like image 235
Meh Avatar asked May 12 '10 13:05

Meh


People also ask

Are pairs ordered in C++?

The pairs in a set are stored in sorted order, sorted by the key i.e. the first value of the pair.

How to define pair C++?

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().

What is std :: pair used for?

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.

Is std :: pair contiguous?

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.


1 Answers

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). 
like image 93
interjay Avatar answered Sep 22 '22 02:09

interjay