0

I am trying to sort a Vector by another Vector.

For Example:

vct1.push_back("need");
vct1.push_back("to");
vct1.push_back("sort");
vct1.push_back("this");

then we habe vct2 which contains:

vct2.push_back("to");
vct2.push_back("need");
vct2.push_back("this");
vct2.push_back("sort"); 
vct2.push_back("other"); //can be ignored
vct2.push_back("string"); //can be ignored

So now i want to sort my vct2 by vct1 the result should be something like this:

vct2->results
_____________
need
to
sort
this
other
string

2 Answers2

0

You need a custom compare, one which finds the position in vec1.

auto find = [&vec1](auto & str){ return std::find(vec1.begin(), vec1.end(), str); };
std::stable_sort(vec2.begin(), vec2.end(), [find](auto & lhs, auto & rhs) { return find(lhs) < find(rhs); };

This will order things not in vec1 at the end, in the order they originally appear. If you don't care what order they appear in, you can instead use std::sort.

Caleth
  • 52,200
  • 2
  • 44
  • 75
  • I don't want to copy the values only to sort. If vct2 doesn't have any values from vct1 then it will be not sorted. :) – the_poq_eht Sep 25 '19 at 08:47
0

You can use iter_swap from <algorithm>. That way you can simply use two loops to do

for ( int i = 0; i < vect1.size(); ++i )
{
    for ( int j = 0; j < vect2.size(); ++j )
    {
        if ( vect2.at( j ) == vect1.at( i ) )
        {
            iter_swap( vect2.begin() + j, vect2.begin() + i );
        }
    }
}

see this for more information on iter_swap

Fade
  • 85
  • 11