我们可以采取“直接引用“方法并使用指向源矢量中值的指针数组。
#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]会给你一个指向原始值,* pointersToValues [I]会给你的价值。
我想你可以通过提供你自己的比较器来使用'std:sort',它可以将目标解引导到目标'std :: vector'中.. – Galik 2014-09-18 20:29:29
请参阅http://stackoverflow.com/questions/1577475/c-sorting - 保持轨道指数 – sfjac 2014-09-18 20:42:52