如何动态分配类的向量? [英] How to allocate dynamically a vector of a class?

查看:117
本文介绍了如何动态分配类的向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习动态记忆并且有一个问题。

假设我有这门课。

I am learning about dynamic memory and have a question.
Let say I have this class.

class Elf {
private:
    double _health = 0;
public:
    Elf(const double &health){_health = health;}
};





我可以创建一个精灵像这样使用智能指针的对象。



I can create an Elf object using smart pointer like this.

unique_ptr<Elf> vec1 = make_unique<Elf>(90);





主要是不使用指针,我使用这一行制作矢量。



In main, without using pointers, I make the vector using this lines.

vector<Elf> vec2;
for (auto i = 0 ; i < 10000; i++){
    vec2.push_back(90);
}





我还有很多需要学习的东西。

如何动态分配矢量Elf类?



I still have lots to learn.
How can I dynamically allocate a vector of Elf class?

推荐答案

从你的例子中我猜你是在问如何构造unique_ptr的向量给Elf并填充。像这样:



From your example I am guessing you are asking how to construct the vector of unique_ptr's to Elf and populate. Like so:

vector<unique_ptr<Elf>> vec_uniqptrElf;

for (auto i = 0; i < 10000; ++i) {

    vec_uniqptrElf.push_back(
        unique_ptr<Elf>(new Elf(90)));
}


你刚刚这样做:)

当你推送时,向量已经在内部动态分配进入它。



如果你想到类似



You are just doing this :)
Vector already internally dynamically allocates when you push_back into it.

If you think about something like

vector<Elf> * pVec = new vector<Elf> (size);





所以你不需要它:vector已经是动态分配过程的包装器,所以动态分配向量就像一个双重正面。这是多余的。



看看: http://stackoverflow.com/questions/6775643/allocating-vectors-or-vectors-of-vectors-dynamically [ ^ ]


这篇关于如何动态分配类的向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆