从 initializer_list 错误构造 std::map [英] Constructing a std::map from initializer_list error

查看:37
本文介绍了从 initializer_list 错误构造 std::map的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个类构造函数,它将采用一个初始化列表并使用它初始化一个映射,如下所示:

I'm trying to make a class constructor that will take an initializer list and init a map with it like this:

class Test {
    std::map<int, int> m_ints;
public:
    Test(std::initializer_list<std::pair<int, int>> init):
        m_ints(init)
    {}
};

但这会导致很长的错误消息,坦率地说我不明白.我需要进行哪些更改才能完成这项工作?

But that results in a very long error message which I frankly don't understand. What do I need to change to make this work?

推荐答案

std::initializer_list 的模板参数声明为具有类型 std::pair;

Declare the template argument of the std::initializer_list as having type std::pair<const int, int>

这是一个演示程序

#include <iostream>
#include <map>
#include <initializer_list>

class Test {
    std::map<int, int> m_ints;
public:
    Test(std::initializer_list<std::pair<const int, int>> init):
        m_ints(init)
    {}
};

int main()
{
    Test t = { { 1, 2 }, { 2, 3 } };

    return 0;
}

对应的构造函数声明如下

The corresponding constructor is declared the following way

map( initializer_list<value_type>,
     const Compare& = Compare(),
     const Allocator& = Allocator());

而 value_type 的定义类似于

and value_type is defined like

typedef pair<const Key, T> value_type;

因此,您也可以通过以下方式定义类的构造函数

Thus you could define the constructor of your class also the following way

Test( std::initializer_list<std::map<int, int>::value_type> init ) :
      m_ints(init)
{}

这篇关于从 initializer_list 错误构造 std::map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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