We can take a "refers" approach directly and use an array of pointers to values in the source vector.
#include <iostream>
#include <vector>
#include <algorithm>
int main(int argc, const char * argv[]) {
//a source vector, who's order shouldn't be changed
std::vector<int> values = {15, 4, 20, 25, 0, 19, -5};
//a vector of pointers to the values in the source vector
std::vector<int *> pointersToValues;
pointersToValues.reserve(values.size());
for(auto& value : values){
pointersToValues.push_back(&value);
}
//two comparators in form of lambda functions
auto descendingOrderSorter = [](int * i, int * j){
return *i > *j;
};
auto ascendingOrderSorter = [](int * i, int * j){
return *i < *j;
};
//examples of usage
std::cout<<"Sorting in a descending order"<<std::endl;
std::sort( pointersToValues.begin(), pointersToValues.end(), descendingOrderSorter);
for(int i = 0; i < pointersToValues.size(); ++i) {
std::cout << "index: " << i << ", value: " << *pointersToValues[i] << std::endl;
}
std::cout<<"Sorting in an ascending order"<<std::endl;
std::sort( pointersToValues.begin(), pointersToValues.end(), ascendingOrderSorter);
for(int i = 0; i < pointersToValues.size(); ++i) {
std::cout << "index: " << i << ", value: " << *pointersToValues[i] << std::endl;
}
return 0;
}
pointersToValues[i] would give you a pointer to the original value, *pointersToValues[i] would give you the value.