我覺得你真的需要(但糾正我,如果我錯了)是訪問容器的元素以某種順序的方式。
與其重新排列我的原始集合,我會借用數據庫設計中的一個概念:保留一個索引,按照某個標準排序。這個索引是一個額外的間接性,提供了很大的靈活性。
這樣就有可能根據一個類的不同成員生成多個索引。
using namespace std;
template< typename Iterator, typename Comparator >
struct Index {
vector<Iterator> v;
Index(Iterator from, Iterator end, Comparator& c){
v.reserve(std::distance(from,end));
for(; from != end; ++from){
v.push_back(from); // no deref!
}
sort(v.begin(), v.end(), c);
}
};
template< typename Iterator, typename Comparator >
Index<Iterator,Comparator> index (Iterator from, Iterator end, Comparator& c){
return Index<Iterator,Comparator>(from,end,c);
}
struct mytype {
string name;
double number;
};
template< typename Iter >
struct NameLess : public binary_function<Iter, Iter, bool> {
bool operator()(const Iter& t1, const Iter& t2) const { return t1->name < t2->name; }
};
template< typename Iter >
struct NumLess : public binary_function<Iter, Iter, bool> {
bool operator()(const Iter& t1, const Iter& t2) const { return t1->number < t2->number; }
};
void indices() {
mytype v[] = { { "me" , 0.0 }
, { "you" , 1.0 }
, { "them" , -1.0 }
};
mytype* vend = v + _countof(v);
Index<mytype*, NameLess<mytype*> > byname(v, vend, NameLess<mytype*>());
Index<mytype*, NumLess <mytype*> > bynum (v, vend, NumLess <mytype*>());
assert(byname.v[0] == v+0);
assert(byname.v[1] == v+2);
assert(byname.v[2] == v+1);
assert(bynum.v[0] == v+2);
assert(bynum.v[1] == v+0);
assert(bynum.v[2] == v+1);
}
我同意兩個答案,如果你打算可以多次執行此操作,不過您可以使用排序的數組從一開始就攜帶索引值,甚至可以創建一個類,該類可以載入您現在擁有多個向量中的所有數據,並一次對所有數據進行排序。 – 2008-10-25 11:12:32
我知道,這是2015年,但我覺得這是一個超優雅,易於實施的解決方案:http://stackoverflow.com/q/17554242/3093378它實際上與接受的答案類似,但是比較簡單的imo,所以我們可以實現一個`custom_sort`,它返回一個`std :: vector`的索引,類似於MATLAB。 –
vsoftco
2015-03-28 23:24:34
在這裏看到我對一個重複問題的答案:https://stackoverflow.com/questions/838384/reorder-vector-using-a-vector-of-indices/46370247#46370247 – cDc 2017-09-22 17:38:31