0

I try to sort a vector of tuple but I have a strange error:

typedef std::tuple<const std::string, const std::string, const unsigned int> nodesfound;

std::vector<nodesfound> nf;

fil_vector(nf);

std::sort(nf.begin(), nf.end(), [](nodesfound const &n1, nodesfound const &n2) {
        return std::get<2>(n1) < std::get<2>(n2);
    });

the error is:

/usr/bin/../lib/gcc/x86_64-linux-gnu/5.4.0/../../../../include/c++/5.4.0/tuple:299:17: error: no viable overloaded '='_M_head(*this) = std::forward<_Head>(_M_head(__in));

if I remove the sort line my program is perfectly fine

2 Answers 2

1

For sort to work elements must necessarily be assignable; however, your tuple elements are all const, so obviously not assignable. Drop the consts:

using nodesfound = std::tuple<std::string, std::string, unsigned>;

std::vector<nodesfound> nf;
fill_vector(nf);
std::sort(
    nf.begin(), nf.end(),
    [](nodesfound const& n1, nodesfound const& n2) {
        return std::get<2>(n1) < std::get<2>(n2);
    }
);

Online Demo

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

1 Comment

std::sort work with tuple, why the inside of the tuple shoud be const? sort can just swap tuple in the vector? thanck's a lot
0

other way is to get index of sorted elements:

typedef std::tuple< const std::string,  const std::string,  const unsigned int> nodesfound;
std::vector<nodesfound> nf;
fil_vector(nf);
std::vector<int> index(nf.size());
std::iota( index.begin(), index.end(), 0 );
std::sort(index.begin(), index.end(), [&](int n1, int n2) {
    return std::get<2>(nf[n1]) < std::get<2>(nf[n2]);
});

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.