![](/img/trans.png)
[英]Sorting a vector using another vector in C++ without lambda function
[英]Sorting vector of vectors without comparator or lambda function?
今天我遇到了一些我認為不會編譯的 C++ 代碼:
#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;
}
據我所知,C++ 中沒有用於整數向量的默認比較器,因此必須實現自定義比較器或 lambda 函數才能將其傳遞給 sort() 函數。
然而,這段代碼編譯的事實讓我想問這個問題; 是否有整數向量的默認比較器? 有沒有花車、雙打等的? 還是編譯器會自動生成? 需要注意的是,這種對向量的向量進行排序的方式在網上是找不到的。
提前致謝!
從std::sort
上的 cppreference ,對於重載void sort( RandomIt first, RandomIt last );
:
1) 使用
operator<
比較元素。
std::vector<T>
提供operator<
。 它的行為是:
按字典順序比較
lhs
和rhs
的內容。 比較由等效於 std::lexicographical_compare 的函數執行。
不帶比較器的std::lexicographical_compare
重載的行為是:
1) 使用
operator<
比較元素。
因此,只要std::vector<T>
的類型T
與operator<
具有可比性,那么std::vector<T>
就可以與operator<
進行比較,從而與std::sort
兼容。 由於int
與operator<
具有可比性,因此std::vector<int>
也是如此,因此std::vector<std::vector<int>>
。 這些類型中的每一種都可以在沒有顯式比較器的情況下與std::sort
使用。
據我所知,C++ 中沒有向量的默認比較器......
vector
s 定義了比較運算符:
https://en.cppreference.com/w/cpp/container/vector/operator_cmp
std::vector
已經定義了運算符== != < <= > >=
。
由於它是一個模板類,因此您不需要為vector
可以容納的每種可能類型定義operator<
。 如果類型滿足LessThanComparable要求,則會生成它。
由於int
顯然可以與<
進行比較,因此vector<int>
將為它生成operator<
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.