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

  • A+
Category:Languages

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?

 


You can create your own functor to sort your vector in template vector order as explained by below code :

#include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; struct MyComparator {     //static const int x = 9;   const std::vector<std::string> correctOrder{"Item1", "Item2", "Item3", "Item4", "Item5"};   bool operator() (const std::string& first,const std::string& second )   {       auto firstitr = std::find(correctOrder.begin(),correctOrder.end(),first);       auto seconditr = std::find(correctOrder.begin(),correctOrder.end(),second);       return firstitr < seconditr;   } }; void printVector(const std::vector<std::string>& input) {     for(const auto&elem:input)     {         std::cout<<elem<<" , ";     }     std::cout<<std::endl; } int main() {   std::vector<string> incomingVector = {"Item3", "Item5", "Item1"};   std::cout<<"vector before sort... "<<std::endl;   printVector(incomingVector);   std::sort(incomingVector.begin(),incomingVector.end(),MyComparator());   std::cout<<"vector after sort...."<<std::endl;   printVector(incomingVector);   return 0; } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: