fork download
  1. #include <string>
  2. #include <iostream>
  3. #include <functional>
  4. #include <algorithm>
  5. #include <list>
  6. #include <vector>
  7.  
  8. struct A
  9. {
  10. std::string str ;
  11. double number ;
  12.  
  13. // ...
  14. };
  15.  
  16. std::ostream& operator << ( std::ostream& stm, const A& a )
  17. { return stm << "{'" << a.str << "'," << a.number << '}' ; }
  18.  
  19. int main()
  20. {
  21. // const, immutable,
  22. const std::list<A> seq_in_physical_order { { "abc", 23.67 }, { "def", 11.05 }, { "ghi", 17.32 },
  23. { "jkl", 56.78 }, { "mno", 33.12 }, { "pqr", 40.71 } } ;
  24.  
  25. std::vector< std::reference_wrapper< const A > > seq_in_logical_order( seq_in_physical_order.begin(),
  26. seq_in_physical_order.end() ) ;
  27. // perform a logical ordering with respect to the member 'number'
  28. std::sort( seq_in_logical_order.begin(), seq_in_logical_order.end(),
  29. [] ( const A& first, const A& second ) { return first.number < second.number ; } ) ;
  30.  
  31. std::cout << "in physical order:\n-----------------\n" ;
  32. for( const A& a : seq_in_physical_order ) std::cout << a << " @ " << std::addressof(a) << '\n' ;
  33.  
  34. std::cout << "\n\n\nin logical order:\n----------------\n" ;
  35. for( const A& a : seq_in_logical_order ) std::cout << a << " @ " << std::addressof(a) << '\n' ;
  36. std::cout << '\n' ;
  37.  
  38. }
  39.  
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
in physical order:
-----------------
{'abc',23.67} @ 0x92d70a0
{'def',11.05} @ 0x92d70b8
{'ghi',17.32} @ 0x92d70d0
{'jkl',56.78} @ 0x92d70e8
{'mno',33.12} @ 0x92d7100
{'pqr',40.71} @ 0x92d7118



in logical order:
----------------
{'def',11.05} @ 0x92d70b8
{'ghi',17.32} @ 0x92d70d0
{'abc',23.67} @ 0x92d70a0
{'mno',33.12} @ 0x92d7100
{'pqr',40.71} @ 0x92d7118
{'jkl',56.78} @ 0x92d70e8