【问题标题】:Sort vectors of vectors in c++在c ++中对向量的向量进行排序
【发布时间】:2015-02-12 04:31:22
【问题描述】:

我有以下数据结构:

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++ 函数对向量的向量进行排序。我尝试先按大小对它们进行排序,然后使用气泡排序进行最终排序。是否有其他方法可以使用标准库函数在 C++ 中对这些向量进行排序。我正在使用 g++ 编译器 (g++ (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3) 在 ubuntu 12.04 上运行 C++。

【问题讨论】:

  • 哦,对不起,我可能误解了这个词的字典含义
  • 没问题 - 我只是想确保您的问题很清楚。你可以edit这个问题,虽然我对你所描述的类型没有一个好的术语。

标签: c++ sorting vector


【解决方案1】:

基本上,你想做的是:

  1. 第一个排序按pair&lt;&gt; 中第一个vector 的大小。
  2. 然后按字典顺序排序vectors。

你必须为此编写自己的比较器函数。

代码:

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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多