Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a vector of strings in a specific predetermined order?

The problem: I need to sort a vector of strings in exact specific order. Let say we have a constant vector or a array with the exact order:

vector<string> correctOrder = {"Item3", "Item1", "Item5", "Item4", "Item2"};

Next, we have a dynamic incoming vector which will have same Items, but they maybe mixed and less in number.

vector<string> incommingVector = {"Item1", "Item5", "Item3"};

So I need to sort the incomming vector with the order like the first vector, correctOrder, and the result must be:

vector<string> sortedVector = {"Item3", "Item1", "Item5"};

I think the correct order may be represented in a different way, but can't figure out. Can someone help me please?

like image 470
Rosen Karadinev Avatar asked Nov 23 '18 10:11

Rosen Karadinev


People also ask

How do you sort a vector of strings?

Approach: The sort() function in C++ STL is able to sort vector of strings if and only if it contains single numeric character for example, { '1', ' '} but to sort numeric vector of string with multiple character for example, {'12', '56', '14' } one should write own comparator inside sort() function.

How do you sort a vector of string in descending order?

Sorting a vector in descending order can be done by using std::greater <>().


1 Answers

If the default comparison is not enough (lexicographic comparison) then the simplest thing you can do is to provide the sort function with a lambda that tells it which string come first. You can have a unordered_map<string,int> with the strings in your correctorder vector as keys and their corresponding position in the sorted array as values.

The cmp function will simply compare the values of the keys you provide in your incommingVector.

unordered_map<string, int> my_map;
for(int i = 0 ; i < correctorder.size() ; i++)
   my_map[correctorder[i]]=i;

auto cmp =[&my_map](const string& s, const string& s1){
   return my_map[s] < my_map[s1];
}   

sort(incommingVector.begin(), incommingVector.end() , cmp);
like image 80
Davide Spataro Avatar answered Oct 05 '22 03:10

Davide Spataro