使用变量索引排序矢量矢量

时间:2015-10-03 18:59:31

标签: c++ sorting vector

我在使用std sort函数时遇到了一些问题。我想对矢量矢量进行排序,而不使用相同的索引。我知道我可以使用类似的东西:

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

在第一种情况下,我不知道如何将指定的索引包含为myfunction的输入。 在第二种情况下,我虽然将索引作为函数签名的输入包括在内,但我甚至无法使其编译如上所示!

错误:

  

main.cpp:28:39:错误:预期表达式排序(dataset.begin(),dataset.end(),[](常量向量&amp; a,常量向量&amp; b)

2 个答案:

答案 0 :(得分:1)

您可以捕获index并在lambda函数中使用它:

std::vector<std::vector<int>> dataset = ...

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

答案 1 :(得分:1)

  1. lambda函数 - 您可以捕获index变量:

    std::size_t index = 2;
    std::sort(dataset.begin(), dataset.end(),
        [index](const std::vector<int>& a, const std::vector<int>& b) {
            return a[index] < b[index]);
        }); 
    
  2. 功能 - 如果您有

    bool myfunction(const std::vector<int>& a, const std::vector<int>& b, std::size_t index)
    

    你可以std::bind索引到第三个参数:

    using namespace std::placeholders;
    std::size_t index = 2;
    std::sort(dataset.begin(), dataset.end(), std::bind(myfunction, _1, _2, index));
    

    认为这个解决方案不如lambdas,只有当它们不可用时才使用它,或者你会受到严重的对待。