How to insert elements of an std::vector
as value into an std::unordered_map
using emplace
and std::piecewise_construct
. This is my sample code
#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
int main() {
std::unordered_map<std::string, std::vector<int>> umap;
umap.emplace(std::piecewise_construct, std::forward_as_tuple("abc"), std::forward_as_tuple({ 1, 2, 3, 4 }));
}
I'm getting the below error
error: too many arguments to function 'constexpr std::tuple<_Elements&& ...> std::forward_as_tuple(_Elements&& ...) [with _Elements = {}]'
CodePudding user response:
The expression
{ 1, 2, 3, 4 }
Has no implicit type. If you want it to be an initializer list (for constructing a vector) you may write it as
std::initializer_list<int>{ 1, 2, 3, 4 }
CodePudding user response:
The compiler can't know you want to construct a std::vector<int>
from the initializer list you pass to the last std::forward_as_tuple
(namely { 1,2,3,4 }
).
You have to explicitly tell it:
std::forward_as_tuple(std::vector<int>{ 1, 2, 3, 4 })
or, in c 17,
std::forward_as_tuple(std::vector{ 1, 2, 3, 4 })