自定义排序元组向量时出错

时间:2016-07-16 10:10:24

标签: c++ sorting vector lambda

我尝试对元组的向量进行排序,但我有一个奇怪的错误:

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

错误是:

/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));

如果我删除排序行,我的程序完全正常

2 个答案:

答案 0 :(得分:1)

要使sort工作,元素必须是可分配的;但是,您的元组元素都是const,因此显然可分配。删除const s:

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

答案 1 :(得分:0)

其他方法是获取已排序元素的索引:

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