簡體   English   中英

如何在創建列表時將列表存儲在字典中,然后將其清除,然后用於具有不同值的下一個鍵?

[英]How do I store a list in a dictionary when it is being created then cleared and then used for the next key with different values?

我真正想要的是讓每個鍵的值成為一個可供以后使用的任意列表。 給出的代碼只是正在嘗試的示例。

#include <string>
#include <list>
#include <map>

int main(){
  std::map<std::string, std::list<std::string>> myMap;
  std::list<std::string> myList;
  int j = 0;
  while(j<4){
    for(int = 0; i < 6; i++){
      myList.push_back("value");
    }
    myMap.insert(std::pair<std::string, std::list<std::string>("Key", myList));
    myList.clear();
    j++;
  }

  return 0;
}

如果您只想重用myList :1) 在while循環中移動列表聲明,以便在每次迭代中創建一個新的空列表,然后 2) 使用帶有右值引用的 map 下標運算符,以便移動列表進入地圖。

#include <iostream>  // cout
#include <string>
#include <list>
#include <map>

int main() {
  std::map<std::string, std::list<std::string>> myMap{};
  int j = 0;
  while (j < 4) {
    std::list<std::string> myList{};
    for(int i = 0; i < 6; i++) {
      myList.push_back(std::string{"value"} + std::to_string(j) + std::to_string(i));
    }
    myMap[std::string{"Key"} + std::to_string(j)] = std::move(myList);
    j++;
  }

  for (auto&& [key, list_value] : myMap)
  {
      std::cout << key << ": ";
      for (auto&& str : list_value)
      {
        std::cout << str << " ";
      }
      std::cout << "\n";
  }

  return 0;
}

演示

暫無
暫無

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

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