Reputation: 45
Today I came across some C++ code which I thought was not going to compile:
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<vector<int>> vectorOfVectors = { { 2, 3, 5 }, { 1, 2, 3 } };
sort(vectorOfVectors.begin(), vectorOfVectors.end());
return 0;
}
As far as I know, there is no default comparator in C++ for vectors of ints, so one would have to implement a custom comparator or lambda function in order to pass it to the sort() function.
However, the fact that this code compiled made me want to ask this question; is there a default comparator for vectors of ints? Is there one for floats, doubles, and so on? Or does the compiler automatically generate it? It should be noted that this way of sorting a vector of vectors is nowhere to be found online.
Thanks in advance!
Upvotes: 3
Views: 1768
Reputation: 1039
As far as I know, there is no default comparator in C++ for vectors ...
There are defined comparison operators for vector
s:
https://en.cppreference.com/w/cpp/container/vector/operator_cmp
std::vector
has defined operators == != < <= > >=
.
Since it is a template class, you do not need to define operator<
for every possible type that a vector
can hold. If the type meets LessThanComparable requirements, it will be generated.
As int
can obviously be compared with <
, vector<int>
will have operator<
generated for it.
Upvotes: 7
Reputation: 29022
From cppreference on std::sort
, for the overload void sort( RandomIt first, RandomIt last );
:
1) Elements are compared using
operator<
.
std::vector<T>
provides operator<
. Its behavior is :
Compares the contents of
lhs
andrhs
lexicographically. The comparison is performed by a function equivalent to std::lexicographical_compare.
The behavior of the overload of std::lexicographical_compare
that doesn't take a comparator is :
1) Elements are compared using
operator<
.
So as long as the type T
in std::vector<T>
is comparable with operator<
then std::vector<T>
can be compared with operator<
and is thus compatible with std::sort
. Since int
is comparable with operator<
, so is std::vector<int>
and therefore so is std::vector<std::vector<int>>
. Each of those types will work with std::sort
without an explicit comparator.
Upvotes: 10