如何在C++中对三元组进行排序?

xun*_*ang 2 c++ sorting stl

我想知道如何使用C++基于第一列对下面的三元组进行排序?我可以使用std :: map吗?

0 0 1
1 2 0
2 0 3
0 1 4
Run Code Online (Sandbox Code Playgroud)

想要的结果是

0 0 1
0 1 4
1 2 0
2 0 3
Run Code Online (Sandbox Code Playgroud)

小智 7

你可以使用std :: sort on,例如,std :: tuple的向量 - 默认比较是lexicographic,所以第一列最重要.


log*_*og0 5

假设你正在排序 std::vector<std::vector<int>>

C++ 11:

std::sort(begin(vec), end(vec), [](const std::vector<int>& a,
                                   const std::vector<int>& b){
  return a[0] < b[0]; // sorting on the first column only
});
Run Code Online (Sandbox Code Playgroud)

假设你想要词汇顺序:

std::sort(begin(vec), end(vec));
Run Code Online (Sandbox Code Playgroud)