如何将元素插入和迭代到这种映射.C++

How to insert and iterate elements to this kind of map. C++

本文关键字:映射 C++ 迭代 元素 插入      更新时间:2023-10-16

我自己试过。但我做不到。所以,请帮忙。

unordered_map<string, pair<string , vector<int>>> umap;

或者更准确地说,我们如何制作一对可以在地图中使用的字符串和一个向量。

好吧,您可以使用insert函数并将它们作为一对插入(或精确嵌套的对(。 例如 结帐此程序 :

#include <iostream>
#include <vector>
#include <string>
#include <unordered_map>
using namespace std;
int main()
{
unordered_map<string, pair<string , vector<int>>> umap;
//Insert like this
umap.insert(make_pair("first", make_pair("data1",vector<int>(3, 0))));
umap.insert(make_pair("second", make_pair("data2",vector<int>(3, 1))));
//or like this
string s = "new", t= "method";
vector <int> v = {1, 2, 3};
umap.insert(make_pair(s, make_pair(t, v)));
//This will print all elements of umap
for(auto p : umap)
{
cout << p.first << " -> " << p.second.first << " , VECTOR : " ;
for(auto x : p.second.second)
cout << x << ',';
cout << endl; 
}
cout << endl;
//Let's see how to change vector already inside map
auto itr = umap.begin();
cout << "BEFORE : ";
for(auto x : (itr->second).second)
{
cout << x << ',';
}
cout << endl;
//We will push 42 here 
(itr->second).second.push_back(42);
cout << "AFTER : ";
for(auto x : (itr->second).second)
{
cout << x << ',';
}
cout << endl;
}

输出为 :

new -> method , VECTOR : 1,2,3,
second -> data2 , VECTOR : 1,1,1,
first -> data1 , VECTOR : 0,0,0,
BEFORE : 1,2,3,
AFTER : 1,2,3,42,

我希望这有所帮助。

这在很大程度上取决于您正在创建的内容的复杂性。例如,如果你的向量中有一些常量,你可以把它们放在适当的位置:

umap.emplace("s", std::make_pair("s2", std::vector<int>{1, 2, 3, 4}));

然而,更有可能的是,您将以某种复杂的方式制作内部结构。在这种情况下,您可以更轻松地将其作为单独的结构进行。

std::vector<int> values;
values.push_back(1);
auto my_value = std::make_pair("s2", std::move(values));
umap.emplace("s2", std::move(my_value));

使用 move 移动数据可确保最少的复制。

最后,要迭代项目,通常使用range-based for loops

for (const auto& [key, value]: umap) {
std::cout << key << ": ";
const auto& [name, values] = value;
std::cout << name << " {";
for (auto val : values) {
std::cout << val << " ";
}
std::cout << "}n";
}

在这里,您可以查看一个实时示例。