fork download
  1. #include <vector>
  2. #include <iostream>
  3. #include <string>
  4. #include <algorithm>
  5.  
  6. int main()
  7. {
  8. std::vector<std::vector<int>> vect = {{0,2,3},{2,1,5},{1,2,4}};
  9. std::vector<int> row = {3,0,1,2,-1,-2,15};
  10. // new vector: pair of integer -> representing the rows of vect and index
  11. std::vector<std::pair<std::string, int>> newVect;
  12. newVect.reserve(vect.size());
  13.  
  14. int index = 0;
  15. for(const std::vector<int>& each_row: vect)
  16. {
  17. std::string str; // each row of vect to a single integer string
  18. for(const int Integer: each_row) str += std::to_string(Integer);
  19. newVect.emplace_back(std::make_pair(str, index));
  20. ++index;
  21. }
  22. // sort the new vector, according to the whole 2D vector row(which is a single string)
  23. std::sort(newVect.begin(), newVect.end(), [](const auto& lhs, const auto& rhs)
  24. {
  25. return lhs.first < rhs.first;
  26. });
  27. // now you can actually store the sorted vect
  28. vect.clear();
  29. for(auto index = 1; index <= row[0]; ++index)
  30. {
  31. row[index] = newVect[index-1].second; // replace the row indexes which are sorted
  32. std::vector<int> vect_row;
  33. // change each chars of string back to corresponding row elements
  34. for(const char Integer: newVect[index-1].first)
  35. vect_row.emplace_back(static_cast<int>(Integer - '0'));
  36. // store to original vector
  37. vect.emplace_back(vect_row);
  38. }
  39.  
  40. // to print
  41. for(const std::vector<int>& each_row: vect)
  42. {
  43. for(const int Intger: each_row)
  44. std::cout << Intger << " ";
  45. std::cout << std::endl;
  46. }
  47. for(const int it: row) std::cout << it << " ";
  48. return 0;
  49. }
Success #stdin #stdout 0s 4384KB
stdin
Standard input is empty
stdout
0 2 3 
1 2 4 
2 1 5 
3 0 2 1 -1 -2 15