我們可以採取「直接引用「方法並使用指向源矢量中值的指針數組。
#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