Click here to Skip to main content
15,885,918 members
Please Sign up or sign in to vote.
5.00/5 (2 votes)
See more:
I am learning about dynamic memory and have a question.
Let say I have this class.
C++
class Elf {
private:
    double _health = 0;
public:
    Elf(const double &health){_health = health;}
};


I can create an Elf object using smart pointer like this.
C++
unique_ptr<Elf> vec1 = make_unique<Elf>(90);


In main, without using pointers, I make the vector using this lines.
C++
vector<Elf> vec2;
for (auto i = 0 ; i < 10000; i++){
    vec2.push_back(90);
}


I still have lots to learn.
How can I dynamically allocate a vector of Elf class?
Posted
Updated 15-Dec-15 3:01am
v2
Comments
[no name] 15-Dec-15 8:59am    
Dynamically allocating vector is trivial. Are you actually talking about making a vector of dynamically allocated Elf's i.e. a vector of pointers to Elf, which is different.

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

C++
vector<unique_ptr<Elf>> vec_uniqptrElf;

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

    vec_uniqptrElf.push_back(
        unique_ptr<Elf>(new Elf(90)));
}
 
Share this answer
 
v4
Comments
Are Riff 15-Dec-15 10:55am    
Thanks
You are just doing this :)
Vector already internally dynamically allocates when you push_back into it.

If you think about something like

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


so you don't need it: vector is already a wrapper around the process of dynamic allocating, so dynamically allocating vectors is like a double positive. It's redundant.

Take a look: http://stackoverflow.com/questions/6775643/allocating-vectors-or-vectors-of-vectors-dynamically[^]
 
Share this answer
 
v5
Comments
Are Riff 15-Dec-15 13:03pm    
Are all STL containers dynamically allocated?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900