在构造函数初始化列表中向STL Map添加元素? [英] Adding elements to an STL Map in a constructors Initialization List?

查看:350
本文介绍了在构造函数初始化列表中向STL Map添加元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道这是否可能,如果是这样,我会这样做。如果不可能,我只需要在构造函数体中添加元素。

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.

理想情况下,我希望在构造之后map不可变。

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.

推荐答案

可以通过拷贝构造:调用构建地图的函数!

It's possible, by copy construction: invoke a function which build the map!

std::map<int,int> myFunc(int a, int b);

class MyObject
{
public:
  MyObject(int a, int b): m_map(myFunc(a,b)) {}

private:
  std::map<int,int> m_map;
};

这篇关于在构造函数初始化列表中向STL Map添加元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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