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


基础教程推荐
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01