用vector保存对象时保存指针的优点, 以及reserve的使用
来源:互联网 发布:安卓6.0mac地址修改器 编辑:程序博客网 时间:2024/06/02 00:37
代码1
- #include <vector>
- #include <stdio.h>
- class A
- {
- public:
- A()
- {
- printf("A()/n");
- }
- ~A()
- {
- printf("~A()/n");
- }
- A(const A& other)
- {
- printf("other/n");
- }
- };
- int main()
- {
- A a;
- A b(a);
- A c = a;
- return 0;
- }
执行结果1
- A()
- other
- other
- ~A()
- ~A()
- ~A()
代码2
- #include <vector>
- #include <stdio.h>
- class A
- {
- public:
- A()
- {
- printf("A()/n");
- }
- ~A()
- {
- printf("~A()/n");
- }
- A(const A& other)
- {
- printf("other/n");
- }
- };
- int main()
- {
- A a;
- A b(a);
- A c = a;
- printf("----------/n");
- std::vector<A> vec;
- //vec.reserve(3);
- vec.push_back(a);
- vec.push_back(b);
- vec.push_back(c);
- return 0;
- }
结果2
- A()
- other
- other
- ----------
- other
- other
- ~A()
- other
- other
- other
- ~A()
- ~A()
- other
- other
- other
- other
- ~A()
- ~A()
- ~A()
- ~A()
- ~A()
- ~A()
- ~A()
- ~A()
- ~A()
把代码2注释掉的vec.reserve(3)打开, 结果3
- A()
- other
- other
- ----------
- other
- other
- other
- ~A()
- ~A()
- ~A()
- ~A()
- ~A()
- ~A()
说明在使用vector时, 插入的是要插入的对象的拷贝, 如果vector中的类对象比较大时, 会影响性能, 还有使用拷贝构造时的一些深浅拷贝的问题, 另外通过结果2与结果3的比较我们可以知道当vector开始申请的空间不够使用时, 它会再次申请空间并可能放弃原来申请的空间, 这样调用的拷贝构造次数就更多了, 所以我们在使用vector前应该通过它的成员函数reserve事先申请一个我们估计的值, 你可以放心, 当reserve的空间不够大时, vector仍然会自动申请空间
下面是使用vector中存放类指针的做法, 一定要注意插入vector中对象指针指向内容的生存周期问题, 另外如果是new出来的, 如果其他地方没有delete应该在适当的时候通过遍历vector查找出来进行delete
- #include <vector>
- #include <stdio.h>
- class A
- {
- public:
- A()
- {
- printf("A()/n");
- }
- ~A()
- {
- printf("~A()/n");
- }
- A(const A& other)
- {
- printf("other/n");
- }
- };
- int main()
- {
- A *a = new A;
- A *b = new A(*a);
- A *c = new A(*a);
- printf("----------/n");
- std::vector<A*> vec;
- vec.reserve(3);
- vec.push_back(a);
- vec.push_back(b);
- vec.push_back(c);
- std::vector<A*>::iterator iter = vec.begin();
- for (; iter!=vec.end(); ++iter)
- {
- delete *iter; //*iter = a , b, c
- }
- vec.clear();
- return 0;
- }
结果
- A()
- other
- other
- ----------
- ~A()
- ~A()
- ~A()
- 用vector保存对象时保存指针的优点, 以及reserve的使用
- 用vector保存对象时保存指针的优点, 以及reserve的使用
- 用vector保存对象时保存指针的优点, 以及reserve的使用
- MAP在保存对象时候的优点
- MAP在保存对象时候的优点
- 声明vector对象保存函数指针
- 声明vector对象保存函数指针
- 保存指针而不是对象的STL容器
- Python列表List保存对象的指针
- Vector的使用:resize、size、reserve、capacity
- vector的reserve和resize以及capacity和size
- 密码保存在Keychan比NSUserDefaults里的优点 (Touch ID以及1Password)
- 使用 vector保存mat
- C++中Vector保存 原始指针和智能指针的析构问题
- vector的reserve和resize
- vector的reserve和resize
- vector的reserve和resize
- vector的reserve和resize
- 使用浏览器兼容的方式创建 异步对象
- HTTP 状态代码的完整列表
- DbHelperSQL.cs--邹老师总结
- oom-kill分析
- ubuntu11.10下 qt Creator 无法在模块路径中找到主题引擎:“pixmap” 以及 Gtk-WARNING **: 无法在模块路径中找到主题引擎:“pixmap”?
- 用vector保存对象时保存指针的优点, 以及reserve的使用
- Visited的小小总结
- oom-kill分析
- 智联简历自动刷新程序
- 并发控制
- 被微软鲍尔默怒摔椅子的人:构建21世纪的Linux
- 大数据技术炙手可热 专业人才短缺成发展掣肘
- SOAP在java中的应用实例
- 树形结构的数据库表Schema设计