Hello,
I am having a bit of brain freeze today and cannot figure out the best way to implement this using the STL algorithms. I have these two vectors
Code:
vector<string> valuesToSort = {"aa", "cc", "bb"};
vector<string> orderToFollow = {"cc", "bb", "gg", "ii", "aa"};
I want to sort valuesToSort by orderToFollow. So, using orderToFollow, valuesToSort will be modified to:
Code:
valuesToSort = {"cc", "bb", "aa"};
Or if the values were the other way round:
Code:
vector<string> valuesToSort = {"cc", "bb", "gg", "ii", "aa"};
vector<string> orderToFollow = {"aa", "cc", "bb"};
valuesToSort would be:
Code:
valuesToSort = {"aa", "cc", "bb", "gg", "ii"};
So if a value that do not exist in the valuesToSort their position is maintained relative. I am thinking of stable_sort with a comparitor but not quite sure how to implement it. Heres what I have so far:
Code:
//values are distinct
vector<string> valuesToSort = {"aa", "cc", "bb"};
vector<string> orderToFollow = {"cc", "bb", "gg", "ii", "aa"};
//vector<string> orderToFollow = {"aa", "cc", "bb"};
//vector<string> valuesToSort = {"cc", "bb", "gg", "ii", "aa"};
vector<string> newOrder;
for (int i = 0; i < orderToFollow.size(); ++i)
{
auto val = find(valuesToSort.begin(), valuesToSort.end(), orderToFollow[i]);
if (val != valuesToSort.end())
{
iter_swap(valuesToSort.begin() + i, val);
}
}
cout << "Order to follow:" << endl;
for (auto i : orderToFollow) cout << i << "\t";
cout << endl << endl;
cout << "Values to sort:" << endl;
for (auto i : valuesToSort) cout << i << "\t";
cout << endl<< endl;
cout << "New order:" << endl;
for (auto i : newOrder) cout << i << "\t";
cout << endl<< endl;
This current implementation goes out of bounds on the iter_swap.
All the strings when being searched should be compared case insensitive and there will never be any duplicates of a string in any vector, they will always be unique. So this could be a set container.