fork(1) download
  1. #include <iostream>
  2. #include <vector>
  3. #include <map>
  4. #include <string>
  5. #include <algorithm>
  6. using namespace std;
  7.  
  8. // create vector holding desired ordering
  9. vector<string> order({ "a", "d", "i", "n", "ns", "ne", "vl", "rr" });
  10.  
  11. // create sort function for vector of pairs
  12. bool comparator(const pair<string, string> &s1, const pair<string, string> &s2) {
  13. // find() - it.begin() gives you the index number.
  14. int a = find(order.begin(), order.end(), s1.first) - order.begin();
  15. int b = find(order.begin(), order.end(), s2.first) - order.begin();
  16. return a < b; // lower index < higher index
  17. };
  18.  
  19. int main() {
  20. // create the map
  21. map<string,string> MyMap = { { "a","legato" }, { "vl","3" }, {"i", "3"}, { "rr","2" } };
  22.  
  23. // convert map into vector of pairs
  24. vector<pair<string,string>> vp;
  25. for (auto& it : MyMap) vp.push_back({ it.first, it.second });
  26.  
  27. // sort the vector
  28. sort(vp.begin(), vp.end(), comparator);
  29.  
  30. // put the vector pairs into a string format
  31. for (auto& it : vp) cout << it.first << "=" << it.second << " ";
  32.  
  33. return 0;
  34. }
Success #stdin #stdout 0s 3424KB
stdin
Standard input is empty
stdout
a=legato i=3 vl=3 rr=2