如何相对于另一个向量对向量进行排序? [英] How do I sort a vector with respect to another vector?
问题描述
我有几个具有相同数据类型的向量.
I have few vectors with same data type as.
v < int > = {5,4,1,2}
v2 < int > = {2,4,3,5,1,6,8,7}
v3 < int > = {1,4,2,3}
有任何方法可以对向量 v2 , v3 ... 进行排序,相对于向量 v 使用 C++ 的 STL(算法)
以便
There is any way to sort vector v2 , v3 ... with respect to vector v using STL of C++(algorithm)
so that
排序后 v2 将是 {5,4,1,2,3,6,7,8},当它相对于 v 排序时,v3 将是 {4,1,2,3} 当它相对于排序时对 .
after sorting v2 would be {5,4,1,2,3,6,7,8} when it's sorted with respect to v and v3 would be {4,1,2,3} when it's sorted with respect to v .
Edit:
有些人可能不清楚.让我解释一下..
排序向量有两个部分,一个是 A,另一个是 B.
A 包含向量 v 的元素,即 A 是 v 的子集,它遵循与 v
中相同的顺序B 包含给定向量 (v_i) 的剩余元素 {v_i - A} 并且它已排序.
所以对于排序后的向量 v2 将是
It may be unclear for some people.
let me explain ..
sorted vector has two parts , one is A and another one is B .
A contains element of vector v i.e. A is subset of v ,it follows same order as it's in v
B contains remaining element{v_i - A} of given vector(v_i) and it's sorted .
so for vector v2 after sorting it would be
v2 = A union B
A = {5,4,1,2}
B = {3,6,7,8}
推荐答案
class StrangeComparison {
public:
StrangeComparison(const vector<int>& ordering) : ordering_(ordering) {}
bool operator()(int a, int b) const {
auto index_a = find(ordering_.begin(), ordering_.end(), a);
auto index_b = find(ordering_.begin(), ordering_.end(), b);
return make_pair(index_a, a) < make_pair(index_b, b);
}
private:
const vector<int>& ordering_;
};
sort(v2.begin(), v2.end(), StrangeComparison(v));
工作示例.提高效率留给读者作为练习(提示:查看 std::find
调用).
Working example. Improving efficiency is left as an exercise for the reader (hint: look at std::find
calls).
这篇关于如何相对于另一个向量对向量进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!