更新时间:2023-11-18 13:57:22
要对数据进行排序,但只有索引显示排序顺序,您需要做的就是创建一个以升序排列的索引数组(从0开始),然后将其用作std::sort
标准的一部分.
To sort the data, but only have the indices show the sort order, all you need to do is create an array of indices in ascending order (starting from 0), and then use that as part of the std::sort
criteria.
这里是一个例子:
#include <algorithm>
#include <iostream>
#include <array>
void test()
{
std::array<double, 8> tumor = {{4, 3, 7, 128,18, 45, 1, 90}};
std::array<int, 8> indices = {0,1,2,3,4,5,6,7};
//sort tumor in ascending order
std::sort(indices.begin(), indices.end(), [&](int n1, int n2)
{ return tumor[n1] < tumor[n2]; });
// output the tumor array using the indices that were sorted
for (size_t i = 0; i < tumor.size(); ++i)
std::cout << tumor[indices[i]] << "\n";
// show the indices
std::cout << "\n\nHere are the indices:\n";
for (size_t i = 0; i < tumor.size(); ++i)
std::cout << indices[i] << "\n";
}
int main()
{ test(); }
即使示例使用std::array
,原理也相同.根据数据中的项目对索引数组进行排序. tumor
数组保持不变,而无需移动实际元素.
Even though the example uses std::array
, the principle is the same. Sort the index array based on the items in the data. The tumor
array stays intact without the actual elements being moved.
如果数组(或std::vector
)中的项目在移动时复制起来很昂贵,但仍希望能够在不实际对项目进行排序的情况下生成已排序的列表,则也可以使用此技术.
This technique can also be used if the items in the array (or std::vector
) are expensive to copy if they're moved around, but still want to have the ability to produce a sorted list without actually sorting items.