emplace_back无法与std :: vector< std :: map< int,int>>一起使用。 [英] emplace_back not working with std::vector<std::map<int, int>>

查看:79
本文介绍了emplace_back无法与std :: vector< std :: map< int,int>>一起使用。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 emplace_back 制成 std :: vector< std :: map< int,int>> ,但找不到正确的语法。

I am trying to do emplace_back into a std::vector<std::map<int, int>>, but could not find the right syntax to do it.

#include<map>
#include<vector>

int main()
{
    std::vector<std::map<int, int>> v;
    std::map<int,int> a {{1,2}};

    v.push_back({{1,2}});

    v.emplace_back({1,2});    // error
    v.emplace_back({{1,2}});  // error
    v.emplace_back(({1,2}));  // error
}

push_back 在这里有效,但 emplace_back 无效。如何获得 emplace_back 的工作?

push_back works here, but not emplace_back. How can I get emplace_back working?

推荐答案

一个人可以使用

 #include <map>
 #include <vector>

 void emplace_work_around(
    std::vector<std::map<int, int>>& v,
    std::initializer_list<std::pair<const int,int>> && item
 )
 {
    v.emplace_back(std::forward<std::initializer_list<std::pair<const int,int>>>(item));
 }

int main()
{
    std::vector<std::map<int, int>> v;

    emplace_work_around(v,{{1,2}});
}

问题是我们写的时候:

v.emplace_back({{1,2}});  // here {{1,2}} does not have a type.

编译器无法推断出参数的类型,并且无法确定哪个构造函数

the compiler is not able to deduce the type of the argument, and it can't decide which constructor to call.

其基本思想是,当您编写类似

The underlying idea is that when you write a function like

template<typename T>
void f(T) {}

并像

f( {1,2,3,4} ); //error

您将得到编译器错误,因为{1,2,3,4}确实有

you will get compiler error, as {1,2,3,4} does have a type.

但是如果您将函数定义为

But if you define your function as

template<typename T>
void f(std::initializer_list<T>) {}
 f( {1,2,3,4} );

然后它可以完美地编译。

then it compiles perfectly.

这篇关于emplace_back无法与std :: vector&lt; std :: map&lt; int,int&gt;&gt;一起使用。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆