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

时间:2012-08-05 18:00:35

标签: c++ sorting stl

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

0 0 1
1 2 0
2 0 3
0 1 4

想要的结果是

0 0 1
0 1 4
1 2 0
2 0 3

2 个答案:

答案 0 :(得分:7)

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

答案 1 :(得分: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
});

假设你想要词汇顺序:

std::sort(begin(vec), end(vec));