簡體   English   中英

以指針為鍵復制 std::map

[英]copying std::map with pointer as key

如果我有以下 C++ class:

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

如果我使用復制構造函數進行深度復制,我將如何確保復制鍵中指針的內容,同時確保每個鍵都與相同的評估結構作為值匹配? 目前我有:

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" }
  }
}

由此,完全相同的地址將存儲在密鑰中,但我不確定如何使密鑰指向不同的地址,但仍指向相同的內容。 我知道將鍵用作指針似乎很奇怪,但我的作業中有一個特定的原因需要這樣做。

通過new和 T 的復制構造函數創建新的 T 對象。 但請記住,map 中的訂單將在復制的 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;
   }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM