我在使用 std 排序函数时遇到了一些问题。我想对 vector 的 vector 进行排序而不总是使用相同的索引。我知道我可以使用类似的东西:
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]);
});
在第一种情况下,我不知道如何将指定的索引作为 myfunction
的输入。
在第二种情况下,我虽然将索引作为函数签名的输入,但我什至不能像上面所示那样编译它!
错误:
main.cpp:28:39: error: expected expression sort(dataset.begin(), dataset.end(), [](const vector& a, const vector& b)
最佳答案
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]); });
函数 - 如果你有
bool myfunction(const std::vector<int>& a, const std::vector<int>& b, std::size_t index)
你可以
std::bind
第三个参数的索引:using namespace std::placeholders; std::size_t index = 2; std::sort(dataset.begin(), dataset.end(), std::bind(myfunction, _1, _2, index));
认为此解决方案不如 lambda,只有在它们不可用时才使用它,否则您会受到不好的对待。
关于c++ - 使用变量索引对 vector 的 vector 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32926310/