Daqs
Daqs

Reputation: 964

Vector as key value pair in Hash map

I'm trying to create a hash_map in C++ with one of the key-value pair of type std::vector. What I'm not getting is how to insert multiple values in vector part of the hash-table?

hash_map<string, int> hm;
hm.insert(make_pair("one", 1));
hm.insert(make_pair("three", 2));

The above example is a simple way of using hash map without vector as a key-pair value.

The example below uses Vector. I am trying to add multiple int values for each corresponding string value, e.g. => "one" & (1,2,3) instead of "one" & (1).

hash_map<string, std::vector<int>> hm;
hm.insert(make_pair("one", ?)); // How do I insert values in both the vector as well as hash_map
hm.insert(make_pair("three", ?)); // How do I insert values in both the vector as well as hash_map

If you're wondering why use vectors here, basically I'm trying to add multiple values instead of a single int value foreach corresponding string value.

Upvotes: 1

Views: 9816

Answers (3)

qPCR4vir
qPCR4vir

Reputation: 3571

here compiled

#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>

int main()
{
  std::unordered_map<std::string, std::vector<int> > hm;
  hm["one"]={1,2,3};
  hm["two"]={5,6,7};
  for (const auto&p : hm)
  {
     std::cout<< p.first << ": ";
     for (const auto &i : p.second)
        std::cout<< i << ", ";
     std::cout<<  std::endl;
  }
}

This output:

two: 5, 6, 7,

one: 1, 2, 3,

The previous answers are basically right (I just didn't tested). In the core they use a vector constructor which take an initialization list which is the only way to directly create the vector enumerating the values. Nevertheless, I wanted to show what I think is a better way to do what you actually want - to set a new value for a given string key.

The operator[string] for this container return a reference for a corresponding value, here vector<int>. If the key is new it first create a new value (vector) too, and insert that pair. Then, the operator= of the vector<int> will assign from the initialization list. I would said you should use the other variants over this direct variant only if you find a serious reason not to use this, because this is more idiomatic and far more direct.

Upvotes: -2

James Adkison
James Adkison

Reputation: 9602

You can do the following:

std::unordered_map<std::string, std::vector<int>> hm;
hm.emplace("one", std::vector<int>{ 1, 2, 3 });

If you want to add to it later you can perform:

hm["one"].push_back(4);

Upvotes: 3

kiviak
kiviak

Reputation: 1103

hash_map<string, std::vector<int>> hm;
hm.insert(make_pair("one", vector<int>{1,2,3})); // How do I insert values in both the vector as well as hash_map
hm.insert(make_pair("three", vector<int>{4,5,6}));

Upvotes: 4

Related Questions