在 C++ 中使用另一个向量对一个向量进行 Lambda 排序

Lambda sorting of one vector using another vector in C++

我正在尝试使用相应的双精度向量 x_values 对向量 x2 中的 int 索引列表进行排序。我在 x2 上使用 std::sort 使用比较器查看 x_values。但是,输出不是我所期望的,我也不知道为什么。

下面是一些示例代码来说明我在说什么:

#include <iostream>
#include <string>
#include <vector>
#include <numeric>
#include <algorithm>

int main()
{
    int numParticles = 2;
    std::vector<double> x_values(4);

    std::vector<int> x2(4);

    std::iota(x2.begin(), x2.begin() + numParticles, 0);
    std::iota(x2.begin() + numParticles, x2.end(), 0);

    x_values = { -0.3,-0.2,-0.1,1.0 };

    std::cout << "\nx values presort: \n";
    for (int i = 0; i < 4; i++) {
        std::cout << x_values[i] << " " << x2[i] << "\n";
    }

    std::sort(x2.begin(), x2.end(), [&x_values](int i1, int i2) {return x_values[i1] < x_values[i2]; });

    std::cout << "\nx index post sort: \n";
    for (int i = 0; i < 4; i++) {
        std::cout << x2[i] << "\n";
    }
}

第一个输出结果为:

x values presort: 
-0.3 0
-0.2 1
-0.1 0
1 1

而第二个输出为:

x index post sort: 
0
0
1
1

我期待第二个输出:

x index post sort: 
0
1
0
1

谁能看出我做错了什么?

x2 中的值 0 被排序为 x_values[0] 又名 -0.3
x2 中的值 1 被排序为 x_values[1] 又名 -0.2

所以排序后的向量是0 0 1 1对应-0.3 -0.3 -0.2 -0.2

我不明白你的困惑,为什么你期待别的东西。


让我重述一下你的比较器的作用:

i1 from x2 comes before i2 from x2 if x_values[i1] < x_values[i2]