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?
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.
Sorting a vector in descending order can be done by using std::greater <>().
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With