Home > Blockchain >  How do I store a list in a dictionary when it is being created then cleared and then used for the ne
How do I store a list in a dictionary when it is being created then cleared and then used for the ne

Time:11-14

What I really want is to have the values to each key be an arbitrary list that is accessible for later use. The code given is just a sample of what is being attempted.

#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;
}

CodePudding user response:

If you just want to reuse myList: 1) move the list declaration inside the while loop, so that a new empty list is created in every iteration, and then 2) use the map subscript operator with an rvalue reference so that the list is moved into the 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;
}

Demo

  • Related