-->

How do I sort a vector with respect to another vec

2019-09-02 10:21发布

问题:

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}

There is any way to sort vector v2 , v3 ... with respect to vector v using STL of C++(algorithm) so that

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:

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} 

回答1:

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));

Working example. Improving efficiency is left as an exercise for the reader (hint: look at std::find calls).



回答2:

You only need to augment your comparison function with the following rules:

  1. if the first value exists in the vector to sort with respect to, but the second value does not exist in it, then first < second
  2. if the second value exists but the first does not, then second < first
  3. if both values exist, compare their index values within that vector

If none of those conditions are true, the existing comparison logic would run.