fork(6) download
  1. #include <iostream>
  2. #include <map>
  3. using namespace std;
  4.  
  5. class SomeClass {
  6. public:
  7. SomeClass(const std::string& name): m_name(name) {}
  8. std::string GetName()const {return m_name; }
  9. bool operator <(const SomeClass& rhs) const
  10. {
  11. return m_name < rhs.m_name;
  12. }
  13. private:
  14. std::string m_name;
  15. };
  16.  
  17. auto print_seq = [](const auto& seq) { for (const auto& itr: seq) {std::cout << itr.second << ":";} std::cout << std::endl;};
  18.  
  19. int main() {
  20. // your code goes here
  21. std::map<SomeClass*, std::string> pointer_keyed_map;
  22. SomeClass s3("object3");
  23. SomeClass s1("object1");
  24. SomeClass s2("object2");
  25. pointer_keyed_map.insert(std::make_pair(&s1, s1.GetName()));
  26. pointer_keyed_map.insert(std::make_pair(&s2, s2.GetName()));
  27. pointer_keyed_map.insert(std::make_pair(&s3, s3.GetName()));
  28. std::cout << "Pointer based keys: object order" << std::endl;
  29. print_seq(pointer_keyed_map);
  30.  
  31. std::map<SomeClass, std::string> int_keyed_map;
  32. int_keyed_map.insert(std::make_pair(s3, s3.GetName()));
  33. int_keyed_map.insert(std::make_pair(s1, s1.GetName()));
  34. int_keyed_map.insert(std::make_pair(s2, s2.GetName()));
  35. std::cout << "String based keys: object order" << std::endl;
  36. print_seq(int_keyed_map);
  37. return 0;
  38. }
Success #stdin #stdout 0s 3460KB
stdin
Standard input is empty
stdout
Pointer based keys: object order
object3:object1:object2:
String based keys: object order
object1:object2:object3: