简体   繁体   中英

Sort vector of vector using variable index

I'm having some problems using the std sort function. 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 . 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)

You could capture index and use it within the lambda function:

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:

     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:

     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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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