将元素添加到构造函数初始化列表中的 STL 映射?
我想知道这是否可能,如果可以的话我将如何去做。如果不可能,我只需在构造函数主体中添加元素即可。
理想情况下,我希望地图在构建后不可变。
我想要实现的是将两对添加到从构造函数参数创建的映射中。
I was wondering if this was possible, and if so how I'd go about doing so. If it's not possible I'll just have to add the elements during the constructor body.
Ideally I would like the map immutable after construction.
What I'm trying to achieve is adding two pairs to the map that are created from constructor parameters.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
通过复制构造,这是可能的:调用构建地图的函数!
It's possible, by copy construction: invoke a function which build the map!
如果没有额外的工具,您只能在初始化列表中初始化 std 容器,只要它们的构造函数支持您即可。如果您需要更多,
map_list_of( )
Boost.Assign 等人做得很好。Boost.Assign 实际操作:
编辑:更新为
std::map
示例。Without extra tools you can only init std containers in initialization lists as far as their constructors support you. If you need more,
map_list_of()
et al from Boost.Assign do a great job.Boost.Assign in action:
edit: updated to
std::map
example.有一个映射构造函数将范围作为一对迭代器。使用它,您可以构建类似于您的需求的东西:
当然,不漂亮。
C++ 的下一个版本将对初始化列表提供更好的支持。在那之前,Boost.Assign 是第二好的选择。
There’s a map constructor that takes a range as a pair of iterators. Using that, you can construct something similar to your demands:
Granted, not pretty.
The next version of C++ will come with better support for initialization lists. Until then, Boost.Assign is the next best thing.
我使用初始化器类:
然后使用它:
这是免费的(从某种意义上说,您不需要构建地图,复制它,然后扔掉第一个地图),因为 C++ 的 返回值优化。初始化向量或其他标准容器也可以做同样的事情。
希望有帮助!
I use an initializer class:
Then to put it to use:
This is free (in the sense that you aren't building a map, copying it, and throwing the first away) because of C++'s return value optimization. The same thing can be done for initializing a vector or other standard containers.
Hope that helps!