Constructing a std::map from initializer_list error(从 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从 initializer_list 错误构造 std::map


基础教程推荐
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 常量变量在标题中不起作用 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09