std vector容器快速添加元素和快速复制的方法

demo

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

struct Point
{
    float x, y, z;
    Point():x(0.0), y(0.0), z(0.0){}
};

int main (int argc, char** argv)
{
    const int num = 5000000;

    / test vector perfermance when add element ///  
    /* demo0 */
    clock_t t0 = clock();
    vector<Point> points1;
    for (int i = 0; i < num; i++)
    {
        points1.push_back(Point());
    }
    clock_t t1 = clock();
    cout<<"push_back directly cost time : "<<(t1-t0)/1000<<"[ms]"<<endl;

	 /* demo1 */
    vector<Point> points2;
    points2.reserve(num);
    for (int i = 0; i < num; i++)
    {
        points2.push_back(Point());
    }
    clock_t t2 = clock();
    cout<<"push_back after reserve cost time : "<<(t2-t1)/1000<<"[ms]"<<endl;

    /// test vector perfermance when copy element /
     /* demo2 */
    clock_t t3 = clock();
    vector<Point> points3 = points2;
    clock_t t4 = clock();
    cout<<"copy directly cost time : "<<(t4-t3)/1000<<"[ms]"<<endl;

	 /* demo3 */
    vector<Point> points4;
    points4.resize(points2.size());
    copy(points2.begin(), points2.end(), points4.begin());
    clock_t t5 = clock();
    cout<<"use copy function cost time : "<<(t5-t4)/1000<<"[ms]"<<endl;

    return 0;
}

result:

push_back directly cost time : 155[ms]
push_back after reserve cost time : 75[ms]
copy directly cost time : 76[ms]
use copy function cost time : 55[ms]

分析

从demo0和demo1的测试结果来看,demo1的效率明显高于demo0,差异在于demo0是在添加元素的过程中分配内存,因此决定了demo0的方式在添加元素过程中要不断的新分配内存用来存储新元素,存在不断分配内存的过程.而demo1就只在初始化的时候分配过一次内存,后面的push_back更多的就像是在复制,所以效率较高.
从demo2和demo3的测试结果来看,demo3使用算法函数copy()实现了更高效率的复制过程,为什么会有这么高的效率可参考https://en.cppreference.com/w/cpp/algorithm/copy,在对于trival assignment等操作可以直接调用c函数(memmove和memcpy)进行内存的拷贝,而且还有一些其它的优化.

结论

1. 在对vector容器进行元素的添加时,如果在容器容量已知的情况下,可先reserve分配内存,然后在添加,能有效提高效率
2. 在对vector容器进行拷贝时,调用算法库中的copy()函数效率会比直接拷贝高

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值