对c++中向量的向量进行排序
Sort vectors of vectors in c++
我有以下数据结构:
std::vector<std::pair <std::vector<unsigned>,std::vector<unsigned> > > A;
包含以下数据:
((7),(108,109)),
((3),(100,101)),
((9),(111,112)),
((5),(102,103)),
((8),(110)),
((8,2,10),(189)),
((5,7),(121)),
((3,9),(119)),
((10),(114)),
((3,5),(115)),
((3,7),(118)),
((3,10),(120)),
((3,4,5),(122))
现在我只想按以下方式对A的一对向量中的第一个向量进行排序。例如,我从A的一对向量中得到的第一个向量是:
(7),
(3),
(9),
(5),
(8),
(8,2,10),
(5,7),
(3,9),
(10),
(3,5),
(3,7),
(3,10),
(3,4,5)
我想根据第一个向量对A进行排序,这样在最终排序后,我的向量变成:
((3),(100,101)),
((5),(102,103)),
((7),(108,109)),
((8),(110)),
((9),(111,112)),
((10),(114)),
((3,5),(115)),
((3,7),(118)),
((3,9),(119)),
((3,10),(120)),
((5,7),(121)),
((3,4,5),(122)),
**((2,8,10),(189)).**
我知道如何使用std:sort对向量进行排序,但我不知道如何使用标准c++函数对向量的向量进行排序。我试着先按大小对它们进行排序,然后使用bublee排序进行最终排序。是否有其他方法可以使用标准库函数在c++中对这些向量进行排序。我在ubuntu 12.04上使用g++编译器运行C++(g++(ubuntu/Linaro 4.6.3-1ubuntu5)4.6.3)。
基本上,您想要做的是:
- 首先根据
pair<>
中第一个vector
的大小对进行排序 - 然后以字典方式对CCD_ 3进行排序
为此,您必须编写自己的比较器函数。
代码:
bool mySort(const pair<vector<unsigned>,vector<unsigned> > &a , const pair<vector<unsigned>,vector<unsigned> > &b)
{
if (a.first.size() == b.first.size()) {
//If sizes of the vectors are equal
//Sort the graph lexicographically.
return std::lexicographical_compare(a.first.begin(),a.first.end(),b.first.begin(),b.first.end());pair<vector<unsigned>,vector<unsigned> > a
} else {
//Sort by size.
return a.first.size() < b.first.size();
}
}
int main()
{
std::vector<std::pair<std::vector<unsigned>,std::vector<unsigned> > > a;
std::sort(a.begin(),a.end(),mySort);
}
相关文章:
- 将结构向量排序为子组
- C++数组与向量排序(在我的情况下,向量比数组慢~2.5倍(无优化))
- 如何在对向量排序后更改索引值?c++
- C++向量排序给出0作为输出
- 将许多向量排序在一起
- 根据一个向量对多个向量排序
- 编译错误向量排序和联合
- C++我自己的函数进行向量排序
- 将字符串的向量排序为日期"yyyymmdd"
- C++ 通过使用旧向量进行预排序来改进向量排序
- C 向量排序 .h .cpp中的单独文件
- 向量排序-c++
- 将向量排序到一个无序映射c++11中
- 向量的向量排序
- c++向量排序方法编译失败,返回预期表达式
- 如何对bitset向量排序
- 向量排序的基础上只有先
- 我如何以相同的方式对两个向量排序,而条件只使用其中一个向量
- 列表排序和结构体向量排序之间的性能差距.c++
- 如何基于第二个字符串对字符串向量的向量排序