fork download
  1. #include <string>
  2. #include <list>
  3. #include <algorithm>
  4. #include <memory>
  5. #include <iostream>
  6.  
  7. struct A
  8. {
  9. std::string id ;
  10. };
  11.  
  12. bool operator == ( const A& a, const std::string& str ) { return a.id == str ; }
  13. bool operator < ( const A& first, const A& second ) { return first.id < second.id ; }
  14.  
  15. int main()
  16. {
  17. std::list<A> seq { {"one"}, {"two"}, {"three"}, {"four"}, {"five"} } ;
  18.  
  19. auto iter= std::find( std::begin(seq), std::end(seq), "three" ) ;
  20. A& alias = *iter ;
  21. A* ptr = std::addressof(alias) ;
  22.  
  23. const auto dump = [&]
  24. {
  25. for( const auto& s : seq ) std::cout << s.id << ' ' ;
  26. std::cout << '\n' ;
  27. std::cout << iter->id << '/' << alias.id << '/' << ptr->id
  28. << " at address " << ptr << "\n\n" ;
  29. };
  30.  
  31. dump() ;
  32.  
  33. seq.sort() ;
  34. dump() ;
  35.  
  36. seq.insert( iter, { {"six"}, {"seven"}, {"eight"} } ) ;
  37. dump() ;
  38.  
  39. seq.erase( std::find( std::begin(seq), std::end(seq), "four" ),
  40. std::find( std::begin(seq), std::end(seq), "seven" ) ) ;
  41. dump() ;
  42.  
  43. seq.reverse() ;
  44. dump() ;
  45.  
  46. // iterator/reference/pointer to A{"three"} have remained vaild till now
  47. // everything we have done upto here is a list operation
  48. // a list does not move its elements around in memory
  49.  
  50. std::cout << "--------------------------\n" ;
  51.  
  52. std::reverse( std::begin(seq), std::end(seq) ) ;
  53. // iterator/reference/pointer to A{"three"} are now invalidated
  54. // iter no longer 'points' to A{"three"} etc.
  55. // the algorithm does move things around in memory
  56. dump() ;
  57. }
  58.  
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
one two three four five 
three/three/three at address 0x83b10a8

five four one three two 
three/three/three at address 0x83b10a8

five four one six seven eight three two 
three/three/three at address 0x83b10a8

five seven eight three two 
three/three/three at address 0x83b10a8

two three eight seven five 
three/three/three at address 0x83b10a8

--------------------------
five seven eight three two 
seven/seven/seven at address 0x83b10a8