Search code examples
c++sortingvectorstlstl-algorithm

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}

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} 

Solution

  • 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).