c++ - 使用变量索引对 vector 的 vector 进行排序

标签 c++ sorting vector

我在使用 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)

最佳答案

  1. 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]);
        }); 
    
  2. 函数 - 如果你有

    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/

相关文章:

python - 将正方形旋转为向量的法线

c++ - C++中的 Mongoose 服务器

c++ - 为什么编译器选项会影响模板实现的选择?

c++ - 数组中的元素移位

java - 尽管已同步,但 Vector 抛出 ConcurrentModificationException

c++ - 如何在 vector 的前面添加结构?

c++ - 将文件中的行输入到 char 数组中

c++ - 在 Visual Studio 的 C++ 项目中是否可以使用宏来识别当前的 SOLUTION 配置?

c++ - `std::sort` 内部使用了什么魔法让它更快?

vba - 在VBA排序中设置范围