c++ - 为什么 std::sort 假定 std::vector< std::vector<int>> 默认为 std::vector,从而产生错误的结果?

标签 c++ sorting c++11 vector stl

<分区>

我创建了一个 vector vector ,我想根据我定义的参数对它们进行排序。在这里,sort()函数采用定义为 vector<vector<int>> 的变量数据集只是一个vector<int> .谁能解释一下出了什么问题?

此外,即使解决了上述问题,compare()函数仅适用于硬编码索引。如果我想根据不同的索引对其进行排序,我应该怎么做。有没有我可以提及的方法?

#include <iostream>
#include <vector>
#include <algorithm>

//void check_function(std::vector <std::vector <int> > *dataset)
//{
//    std::cout<<(*dataset)[0].size()<<std::endl;
//}

bool compare(const std::vector <std::vector <int> > &a, const std::vector <std::vector <int> > &b)
{
    return a[1] < b[1];
}

/* This works, but this sorts based on the first parameter of the vector rather than what I mention.
bool compare(const std::vector <int> &a, const std::vector <int> &b)
{
    return a < b;
}
*/    
int main()
{
    std::vector <int> data;
    std::vector <int> data2;
    std::vector <std::vector <int> > dataset;

    data.push_back(5);
    data.push_back(10);
    dataset.push_back(data);

    data2.push_back(5);
    data2.push_back(20);
    dataset.push_back(data2);

//    check_function(&dataset);
    std::sort(dataset.begin(), dataset.end(), compare);
    std::cout<< dataset[0][0]<<std::endl;

    return 0;
}

最佳答案

对容器进行排序,您需要一个函数来比较容器中包含的成对元素。

因此,对 std::vector<std::vector<int>> 进行排序, 你需要一个接收一对 std::vector<int> 的函数.

但是你的compare()收到一对 std::vector<std::vector<int>> .

这是错误的。

题外话:你的compare()函数(恕我直言)非常危险,因为访问两个 vector 的第二个元素而不检查它们是否包含至少两个元素。

我认为你至少应该使用 at()相反 operator[] ;只是为了执行绑定(bind)检查,以防万一,获得可捕获的异常;像

bool compare(const std::vector <int> & a, const std::vector <int> & b)
{
    return a.at(1) < b.at(1);
}

--- 编辑 ---

OP 询问

how do I sort it based on an index that is decided in runtime?

如何决定?在哪里?

假设在compare()之外决定(在调用 std::sort() 的函数中,例如),您可以使用 lambda 函数。

一个例子

#include <iostream>
#include <vector>
#include <algorithm>

int main()
 {
   std::vector <std::vector <int> > dataset;

   dataset.emplace_back(std::initializer_list<int>{200, 1});
   dataset.emplace_back(std::initializer_list<int>{5, 56});

   auto val = 1U;

   std::sort(dataset.begin(), dataset.end(),
             [val](const std::vector <int> &a, const std::vector <int> &b)
              { return  a.at(val) < b.at(val); });

   std::cout << dataset[0][0] << ", " << dataset[0][1] << std::endl;

   return 0;
 }

关于c++ - 为什么 std::sort 假定 std::vector< std::vector<int>> 默认为 std::vector,从而产生错误的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41526640/

相关文章:

c++ - 右值引用和完美转发

c++ - 未解析的外部符号 __imp__Inf 和 __imp__Nan

c++ - 两个窗口 - 一个由线程随机输出修改

javascript - 按两个数字字段对 Javascript 数组进行排序

Python 3 - 通过循环重建给定集合来减少列表

c++ - 对重载函数的模糊调用 - std::to_string

c# - 在加载应用程序目录之外的目录中加载依赖于其他程序集的程序集?

c++ - 在 C++ 中创建自己的错误处理机制

java - TreeSet 忽略值

c++ - 重新加载序列点和方法链接