STL 映射值构造函数 [英] STL Map Value Constructors

查看:19
本文介绍了STL 映射值构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 X 类,我想将它放入 std::map 类型的 STL 映射中.STL 映射需要将 X 存储在内存中的某处,因此我正在寻找一种有效的(运行时和内存)方法来创建 X 并将其存储在映射中.

I have a class X that I would like to put into an STL map of type std::map. An STL map needs to have X stored in memory somewhere so I'm looking for an efficient (run time and memory) way to create X and store it in the map.

我注意到以下代码,其中 x 是 X 类型的对象,stlMap 是 std::map 类型的映射:

I noticed that the following code where x is an object of type X and stlMap is a map of type std::map:

stlMap["test"] = x;

调用以下结果:

  1. X 默认构造函数
  2. X 复制构造函数
  3. X 复制构造函数
  4. X 析构函数
  5. X 析构函数
  6. X 赋值构造函数
  7. X 析构函数

为什么要创建这么多 X 对象?

Why are so many X objects being created?

时间和内存的使用效率低下吗?

Is it an inefficient use of time and memory?

有没有更好的方法将对象放入地图中?也许将映射更改为字符串映射到 x*?

Is there a better way to put an object into a map? Maybe changing the map to be a map of strings to x*?

推荐答案

试试 stlMap.insert( map::value_type("test", x) ):

#include <iostream>
#include <string>
#include <map>

using namespace std;

class X
{
public:
X() { cout << "X default constructor" << endl; }
~X() { cout << "X destructor" << endl; }
X( const X& other ) { cout << "X copy constructor" << endl; }
X& operator=( const X& other ) { cout << "X copy-assignment operator" << endl; }
int x;
};


int main()
{
X x;
map< string, X > stlMap;

cout << "INSERT BEGIN" << endl;
stlMap.insert( map< string, X >::value_type( "test", x ) );
cout << "INSERT END" << endl;
stlMap.clear();
cout << "ASSIGN BEGIN" << endl;
stlMap["test"] = x;
cout << "ASSIGN END" << endl;

return 0;
}

在我的 g++ 上,将事情简化为:

On my g++ that whittles things down to:

  1. X 拷贝构造函数
  2. X 拷贝构造函数
  3. X 析构函数

根据 ArunSaha 的建议,更新了测试.insert() 输出不变,而赋值序列如下所示:

Per ArunSaha's suggestion, updated the test. The insert() output is unchanged, while the assignment sequence looks like this:

  1. X 默认构造函数
  2. X 拷贝构造函数
  3. X 拷贝构造函数
  4. X 析构函数
  5. X 析构函数
  6. X 复制赋值运算符

这篇关于STL 映射值构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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