fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <iterator>
  4. #include <string>
  5. #include <algorithm>
  6. #include <numeric>
  7.  
  8. using namespace std;
  9.  
  10. template<typename It>
  11. void replace(
  12. It beg,
  13. It end,
  14. typename iterator_traits<It>::value_type const& oldval,
  15. typename iterator_traits<It>::value_type const& newval)
  16. {
  17. while ((beg = find(beg, end, oldval)) != end)
  18. {
  19. *beg = newval;
  20. ++beg;
  21. }
  22. }
  23.  
  24. template<typename T>
  25. void rearrange_vector(vector<int> nInd, vector<T> &v)
  26. {
  27. size_t indx;
  28. for (size_t ie(v.size()), i(0); i < ie; ++i)
  29. {
  30. auto it = find(nInd.begin(), nInd.end(), i);
  31. if (nInd.end() != it)
  32. {
  33. indx = distance(nInd.begin(), it);
  34. swap(v.at(i), v.at(indx));
  35. replace(nInd.begin(), nInd.end(), indx, i);
  36. }
  37. }
  38. }
  39.  
  40. int main()
  41. {
  42. vector<string> firstnames = { "Bjarne", "Alexander", "Dennis", "James", "James" };
  43. vector<string> lastnames = { "Stroustrup", "Stepanov", "Ritchie", "Coplien", "Gosling" };
  44.  
  45. vector<int> indices(firstnames.size());
  46. iota(indices.begin(), indices.end(), 0);
  47.  
  48. sort(indices.begin(), indices.end(), [&](int i1, int i2){
  49. return firstnames[i1] < firstnames[i2];
  50. });
  51.  
  52. rearrange_vector(indices, firstnames);
  53. rearrange_vector(indices, lastnames);
  54.  
  55. for (size_t i(0), ie(firstnames.size()); i < ie; ++i)
  56. {
  57. cout << firstnames[i] << " " << lastnames[i] << endl;
  58. }
  59.  
  60. return 0;
  61. }
Success #stdin #stdout 0s 3480KB
stdin
Standard input is empty
stdout
Alexander Stepanov
Bjarne Stroustrup
Dennis Ritchie
James Coplien
James Gosling