我有一个类X,我想将其放入std :: map类型的STL映射中.STL映射需要将X存储在某个地方的内存中,所以我正在寻找一种有效的(运行时和内存)方式来创建X并将其存储在地图中.
我注意到下面的代码,其中x是X类型的对象,stlMap是std :: map类型的映射:
stlMap["test"] = x;
Run Code Online (Sandbox Code Playgroud)
调用以下结果:
为什么要创建这么多X对象?
这是时间和记忆的低效利用吗?
有没有更好的方法将对象放入地图?也许将地图更改为x*的字符串映射?
试试stlMap.insert( map<string, X>::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;
}
Run Code Online (Sandbox Code Playgroud)
在我的g ++上,将事情归结为:
编辑:Per ArunSaha的建议,更新了测试.insert()输出未更改,而赋值序列如下所示: