C++的vector优化

1、C++中的动态数组一般是特指vector类

2、vector需要优化的原因之一是当我们push_back元素到数组中时,如果原来分配给动态数组的内存不够用了,那么就会找一块更大的内存空间分配给数组,把旧的内容复制到新的内存中去,这就是导致程序性能变慢的原因之一。

了解我们的环境,是优化过程中最重要的事情之一

以下代码会复制3次

#include<iostream>
#include<string>
#include<vector>

struct Vertex
{
    float x,y,z;
    
    Vertex(float x,float y,float z)
        :x(x),y(y),z(z)
    {
    }
    
    Vertex(const Vertex& vertex)
        :x(vertex.x),y(vertex.y),z(vertex.z)
    {
        std::cout<<"Copied!"<<std::endl;
    }
};

std::ostream& operator<<(std::ostream& stream,const Vertex& vertex) //输出运算法重载
{
    stream << vertex.x <<", "<< vertex.y <<", "<< vertex.z;
    return stream;
}

int main()
{
   // Vertex* vertices = new Vertex[5];//还是基于堆的固定大小的分配
    std::vector<Vertex> vertices;//尖括号中是vertices数组中元素的类型
    vertices.push_back({1,2,3});
    vertices.push_back({4,5,6});//向数组中添加元素
    vertices.push_back({7,8,9});
    std::cin.get();
}

以下代码会复制6次

#include<iostream>
#include<string>
#include<vector>

struct Vertex
{
    float x,y,z;
    
    Vertex(float x,float y,float z)
        :x(x),y(y),z(z)
    {
    }
    
    Vertex(const Vertex& vertex)
        :x(vertex.x),y(vertex.y),z(vertex.z)
    {
        std::cout<<"Copied!"<<std::endl;
    }
};

std::ostream& operator<<(std::ostream& stream,const Vertex& vertex) //输出运算法重载
{
    stream << vertex.x <<", "<< vertex.y <<", "<< vertex.z;
    return stream;
}

int main()
{
   // Vertex* vertices = new Vertex[5];//还是基于堆的固定大小的分配
    std::vector<Vertex> vertices;//尖括号中是vertices数组中元素的类型
    vertices.push_back(Vertex(1,2,3));
    vertices.push_back(Vertex(4,5,6));//向数组中添加元素
    vertices.push_back(Vertex(7,8,9));
    std::cin.get();
}

为什么会发生这种情况呢?

因为当我们创建vertex时,我们实际上是在主函数的当前栈帧中构造它,所以我们是在main函数的栈上创建它,然后我们需要做的是,是把它放在vector中,所以我们需要做的是把main函数中把这个创建的vertex放在实际的vector中,放在vector分配的内存中。

所以我们可以优化的事情之一是:

事先分配好内存

我们可以在适当的位置(也就是vector分配的内存)构造那个vertex

emplace_back()函数就是在告诉vector:嘿,你给我用1,2,3这些参数创建一个vectex类。这样就是在vector所在的内存创建,从而避免了复制。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Invulnerabl_DL

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值