std::vector
可以初始化为
std::vector<std::string> words1 {"the", "frogurt", "is", "also", "cursed"};
现在,如果想为我的一种类型实现类似的功能,我该怎么做呢?我应该如何实现这个功能的构造函数?
标准如何支持我实现这一目标(参考标准将最有帮助)?基本上,如果你能教我如何实现 std::vector
就足够了。
这也可以在 C++11 之前完成吗?
另外,我可以有一个 POD 结构类型初始化器列表,以便我可以使用不同类型的值来初始化我的类型吗?
原文由 Koushik Shetty 发布,翻译遵循 CC BY-SA 4.0 许可协议
创建一个以
std::initializer_list
作为参数的构造函数:std::vector
does this is almost exactly the same way (althoughbegin()
andend()
-std::initializer_list
has iterators much the same way as other containers做)。从gcc
:编辑:我不是你想要做的 100%,但你可以简单地使用 统一初始化 来得到你想要的: