![](/img/trans.png)
[英]In C++, How do I store values into a vector that is inside of a vector when the two vectors are of different types?
[英]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.