基于其他信息的C 排序索引

C++ sorting indices based on other information

本文关键字:排序 索引 信息 于其他 其他      更新时间:2023-10-16

说我有一个顶点列表: std::vector<vec3> vertices和索引列表: std::vector<unsigned int>。然后,我想用std::sort对这些索引进行排序,而不是基于索引的大小,而是基于它们指向的顶点坐标。这就是我的意思:

std::sort(indices.begin(), indices.end(), 
        [](unsigned int indexA, unsigned int indexB) {
            return vertices[indexA].x < vertices[indexB].x;
        });

在一个完美的世界中,以下将根据指向的顶点的x坐标对索引进行分类。但是,这不是Lambda功能的工作方式,我无法访问vertices信息。

有没有办法在上面说明的方式中使用std::sort?还是我最好使用键值数据结构/实现自己的气泡排序?

您只是错过了捕获的捕获,这是lambda的捕获部分中的简单&

std::sort(indices.begin(), indices.end(), 
    [&](unsigned int indexA, unsigned int indexB) {
        return vertices[indexA].x < vertices[indexB].x;
    });

在这里如何工作:http://en.cppreference.com/w/cpp/language/lambda