STL 映射值构造函数

编程入门 行业动态 更新时间:2024-10-20 13:50:29
本文介绍了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;

调用以下结果:

  • X 默认构造函数
  • X 复制构造函数
  • X 复制构造函数
  • X 析构函数
  • X 析构函数
  • X 赋值构造函数
  • 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:

  • X 拷贝构造函数
  • X 拷贝构造函数
  • X 析构函数
  • 根据 ArunSaha 的建议,更新了测试.insert() 输出不变,而赋值序列如下所示:

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

  • X 默认构造函数
  • X 拷贝构造函数
  • X 拷贝构造函数
  • X 析构函数
  • X 析构函数
  • X 复制赋值运算符
  • 更多推荐

    STL 映射值构造函数

    本文发布于:2023-11-16 11:45:28,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1603988.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:函数   STL

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!