問題描述
我有幾個 std::vector
,長度都一樣.我想對這些向量之一進行排序,并對所有其他向量應用相同的轉換.有沒有一種巧妙的方法來做到這一點?(最好使用 STL 或 Boost)?一些向量包含 int
s,其中一些包含 std::string
s.
I have several std::vector
, all of the same length. I want to sort one of these vectors, and apply the same transformation to all of the other vectors. Is there a neat way of doing this? (preferably using the STL or Boost)? Some of the vectors hold int
s and some of them std::string
s.
偽代碼:
std::vector<int> Index = { 3, 1, 2 };
std::vector<std::string> Values = { "Third", "First", "Second" };
Transformation = sort(Index);
Index is now { 1, 2, 3};
... magic happens as Transformation is applied to Values ...
Values are now { "First", "Second", "Third" };
推薦答案
friol 的方法與您的方法結合使用時效果很好.首先,構建一個包含數字 1...n 的向量,以及向量中指示排序順序的元素:
friol's approach is good when coupled with yours. First, build a vector consisting of the numbers 1…n, along with the elements from the vector dictating the sorting order:
typedef vector<int>::const_iterator myiter;
vector<pair<size_t, myiter> > order(Index.size());
size_t n = 0;
for (myiter it = Index.begin(); it != Index.end(); ++it, ++n)
order[n] = make_pair(n, it);
現在您可以使用自定義排序器對這個數組進行排序:
Now you can sort this array using a custom sorter:
struct ordering {
bool operator ()(pair<size_t, myiter> const& a, pair<size_t, myiter> const& b) {
return *(a.second) < *(b.second);
}
};
sort(order.begin(), order.end(), ordering());
現在您已經捕獲了 order
中的重新排列順序(更準確地說,在項目的第一個組件中).您現在可以使用此順序對其他向量進行排序.可能有一個非常聰明的就地變體同時運行,但在其他人提出它之前,這里有一個不是就地變體.它使用 order
作為每個元素新索引的查找表.
Now you've captured the order of rearrangement inside order
(more precisely, in the first component of the items). You can now use this ordering to sort your other vectors. There's probably a very clever in-place variant running in the same time, but until someone else comes up with it, here's one variant that isn't in-place. It uses order
as a look-up table for the new index of each element.
template <typename T>
vector<T> sort_from_ref(
vector<T> const& in,
vector<pair<size_t, myiter> > const& reference
) {
vector<T> ret(in.size());
size_t const size = in.size();
for (size_t i = 0; i < size; ++i)
ret[i] = in[reference[i].first];
return ret;
}
這篇關于如何通過不同 std::vector 的值對 std::vector 進行排序?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!