简体   繁体   English

使用变量索引对向量进行向量排序

[英]Sort vector of vector using variable index

I'm having some problems using the std sort function. 我在使用std排序功能时遇到了一些问题。 I want to sort a vector of vector without using always the same index. 我想对向量的向量进行排序而不使用始终相同的索引。 I know I can use something like: 我知道我可以使用类似:

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

In the first case I don't know how to include the specified index as an input of myfunction . 在第一种情况下,我不知道如何将指定的索引作为myfunction的输入。 In the second case, I though of including the index as an input of the function signature but I can't even make it compile as shown above! 在第二种情况下,尽管我将索引作为函数签名的输入,但我什至不能像上面显示的那样编译它!

The error: 错误:

main.cpp:28:39: error: expected expression sort(dataset.begin(), dataset.end(), [](const vector& a, const vector& b) main.cpp:28:39:错误:预期表达式sort(dataset.begin(),dataset.end(),[](const vector&a,const vector&b)

You could capture index and use it within the lambda function: 您可以捕获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. lambda function - you can capture the index variable: 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. function - if you have 功能 -如果有

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

    you can std::bind index to the third parameter: 您可以将std::bind索引添加到第三个参数:

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

    Consider this solution inferior to lambdas, use it only when they're not available, or you'll be treated badly. 考虑此解决方案不如lambdas,仅在不可用时才使用它,否则您将受到不好的对待。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM