如何向这种地图插入和迭代元素。 C++

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

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

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));

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

最后要迭代items,正常使用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";
}

Here you can check out a live example.