PuperHacker
PuperHacker

Reputation: 45

Sorting vector of vectors without comparator or lambda function?

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

Answers (2)

Rinat Veliakhmedov
Rinat Veliakhmedov

Reputation: 1039

As far as I know, there is no default comparator in C++ for vectors ...

There are defined comparison operators for vectors:

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

Fran&#231;ois Andrieux
Fran&#231;ois Andrieux

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 and rhs 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

Related Questions