简体   繁体   中英

how to insert std::vector elements into an std::unordered_map using emplace

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 = {}]'

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 }

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 ,

std::forward_as_tuple(std::vector{ 1, 2, 3, 4 })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM