user11508332
user11508332

Reputation: 667

copying std::map with pointer as key

If I have the following C++ class:

template <typename T>
class my_class {
 public:
 private:
  struct assessment {
    int mark;
    String grade;
  } std::map<T*, mark> class_map;
}

If I were doing a deep copy with a copy constructor, how would I ensure that the content of the pointers in the keys are copied over, while also making sure each key is matched to the same assessment struct as a value? Currently I've got:

my_class(my_class const& other) {
  typename std::map<T*, mark>::iterator it = other.class_map.begin();
  while (it != other.class_map.end()) {
    class_map[it->first] = Struct assessment { 70, "Credit" }
  }
}

From this, the exact same addresses will be stored in the key, but I'm not sure how to make it so that the keys point to different addresses, but still point to the same content. I know it seems weird to have the keys as pointers, but there's a specific reason in my assignment that I need to do so.

Upvotes: 0

Views: 391

Answers (1)

Łukasz Ślusarczyk
Łukasz Ślusarczyk

Reputation: 1864

Create new T objects by new and T's copy constructor. But keep in mind, that order in map will be lost in copied map.

my_class(my_class const& other) {
   auto it = other.class_map.begin();
   while (it != other.class_map.end()) {
      T* newKey = new T(*it->first);
      class_map[newKey] = it->second;
      ++it;
   }
}

Upvotes: 3

Related Questions