Ramzan
Ramzan

Reputation: 211

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

I tried on my own. But I was unable to do it. So, please help.

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

Or more precisely, how We can make pair of one string and one vector that can be used in map.

Upvotes: 0

Views: 332

Answers (2)

Deep Raval
Deep Raval

Reputation: 407

Well you can use insert function and insert them as a pair (Or precisely nested pairs). For example Checkout this program :

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

Output Is :

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,

I hope this helps.

Upvotes: 1

Fantastic Mr Fox
Fantastic Mr Fox

Reputation: 33864

This depends a lot on the complexity of what you are creating. For example, if you have some constants in your vector, you could make them in place:

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

It is more likely however that you will be making the internals in some complex way. In which case you could more easily do it as separate constructions.

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

Using move to move the data around ensures minimal copying.

Finally, to iterate the items, it is normal to use 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.

Upvotes: 0

Related Questions