michaelAdam
michaelAdam

Reputation: 1137

How do tuples get automatically sorted?

student a = make_tuple(1, "Adam");
student b = make_tuple(3, "Josh");
vect.push_back(a);
vect.push_back(b);
vect.push_back(make_tuple(2, "Daniel"));
sort(vect.begin(), vect.end());

Before sorting they are in order 1, 3, 2 in the vector. After the sort they are in order 1, 2, 3. I did not define a comparator, and the sort is the built in method with no callback function. How does it know how to sort by the integer parameter of the tuple? Is sorting built into tuple?

Upvotes: 0

Views: 128

Answers (1)

Brian Bi
Brian Bi

Reputation: 119641

Tuples have pre-defined comparison operators. They behave the way you would expect; according to the standard (C++11 §20.4.2.7/5), the operator< of a tuple returns "the result of a lexicographical comparison".

Upvotes: 2

Related Questions