你可以做一个
std::vector<int> originalData = getOriginalData();
然后在保留对原始顺序的访问权的同时对其进行排序,只需对
std::vector<int const*> itemPointers;
您可以像这样初始化:
for( auto&& x : originalData )
{
itemPointers.push_back( &x );
}
现在只需排序:
std::sort(
itemPointers.begin(), itemPointers.end(),
[]( int const* p1, int const* p2 ) { return (*p1 < *p2); }
);
完整的代码还显示了访问原始数据前置项的详细信息:
#include <algorithm> // std::sort
#include <iostream>
#include <utility> // std::begin, std:.end
#include <vector> // std::vector
//using namespace std;
std::vector< int > getOriginalData()
{
static int const data[] = {3, 1, 4, 1, 5, 9, 2, 6, 5, 4};
return std::vector<int>( std::begin( data ), std::end( data ) );
}
int main()
{
std::vector<int> const originalData = getOriginalData();
std::vector<int const*> itemPointers;
for( auto const& x : originalData )
{
itemPointers.push_back( &x );
}
std::sort(
itemPointers.begin(), itemPointers.end(),
[]( int const* p1, int const* p2 ) { return (*p1 < *p2); }
);
std::wcout << "Sorted: ";
for( auto const p : itemPointers )
{
std::wcout << *p << " ";
}
std::wcout << std::endl;
std::wcout << "Predecessors in original data: ";
for( auto const p : itemPointers )
{
int const* const pPred = (p == &originalData[0]? nullptr : p - 1);
if( pPred == nullptr )
{ std::wcout << "! "; }
else
{ std::wcout << *pPred << " "; }
}
std::wcout << std::endl;
}