1

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)

1
  • Is it always the same index for one run? Or do you intend to compare for example element 1 of vector 0 with element 20 of vector 1? Commented Oct 3, 2015 at 19:08

2 Answers 2

1
  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.

Sign up to request clarification or add additional context in comments.

4 Comments

Don't use int ... use std::size_t.
I feel compelled to downvote you for mentioning that bind crap. It's superfluous and inferior to lambdas in the vast majority of cases, including this one.
Well, OP asked about that. He/she can also choose between the two.
He didn't ask about that, he just had a generic need to capture or bind a variable. There's nothing std::bind specific in it.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.