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.
Here is an example:
#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]] << "
";
// show the indices
std::cout << "
Here are the indices:
";
for (size_t i = 0; i < tumor.size(); ++i)
std::cout << indices[i] << "
";
}
int main()
{ test(); }
Live Example
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.
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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…