fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <boost/unordered_map.hpp>
  4. #include <boost/functional/hash.hpp>
  5.  
  6. typedef enum
  7. {
  8. P0 = 0,
  9. P1
  10. } Mpol;
  11.  
  12. class MyClass {
  13. public:
  14. MyClass(const std::string& data, Mpol number) : data(data), number(number) {}
  15.  
  16. bool operator==(const MyClass& other) const {
  17. return data == other.data && number == other.number;
  18. }
  19.  
  20. std::string data;
  21. Mpol number;
  22.  
  23. // Define the hash function for MyClass
  24. friend std::size_t hash_value(const MyClass& obj) {
  25. std::size_t seed = 0;
  26. boost::hash_combine(seed, obj.data);
  27. boost::hash_combine(seed, obj.number);
  28. return seed;
  29. }
  30.  
  31. };
  32.  
  33.  
  34.  
  35. int main() {
  36. // Create a boost::unordered_map with MyClass as the key and int as the value
  37. boost::unordered_map<MyClass, int> my_map;
  38.  
  39. MyClass obj1("Hello, world!", P0);
  40. MyClass obj2("Goodbye, world!", P1);
  41.  
  42. // Add key-value pairs to the boost::unordered_map
  43. my_map[obj1] = 1;
  44. my_map[obj2] = 2;
  45.  
  46. // Access and print values in the boost::unordered_map
  47. std::cout << "Value for obj1: " << my_map[obj1] << std::endl;
  48. std::cout << "Value for obj2: " << my_map[obj2] << std::endl;
  49.  
  50. return 0;
  51. }
  52.  
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
Value for obj1: 1
Value for obj2: 2