1

So now i have an array of class objects like this:

    ClassA* object1[10];
object1[0] = new ClassA();
object1[1] = new ClassA();

Now i would like to use schablone:

vector <ClassA> ver(10);

I am not sure if this is correct. Template, but how do i insert new objects into this vector array in main function?

1
  • Why don't you use new [] in example 1? Commented Apr 29, 2016 at 7:41

3 Answers 3

2

how do i insert new objects into this vector array in main function

ver already contains 10 default initialized objects. So you can go and start using the objects. Bonus is you don't need to delete it.

Possible usage ver[3].classAFunc();

If number of objects is fixed and known at compile time, std::array may be better choice over std::vector in most cases.

Sign up to request clarification or add additional context in comments.

Comments

2

You can add them either by pushing back or emplacing back. Example:

std::vector<ClassA*> objects;
objects.push_back(new ClassA());
object1.push_back(new ClassA());

Or you can use an initializer list:

std::vector<ClassA*> objects{{new ClassA(), new ClassA()}};

You still need to remember to delete the objects.

Better would be to have a vector of shared_ptrs.

1 Comment

Thank you for this, but i was looking more for a answer posted by @Mohit Jain . :)
1

Why are you using raw pointers and raw dynamic arrays in the first place?

The C++ way to create the dynamic array in your first line would be the following:

std::vector<ClassA*> object1(10);

This creates a vector with 10 null pointers in it.

The next two lines could be the same, but you'd still have the issue of manually managing the object lifetimes and memory of the ClassA objects. Let's fix that by using smart pointers:

std::vector<std::unique_ptr<ClassA>> object1(10);
object1[0] = std::make_unique<ClassA>();
object1[1] = std::make_unique<ClassA>();

Depending on the circumstances you probably won't need a vector with exactly 10 elements and the last 8 being null pointers. If you want the vector to contain only the elements that are actually set, then do not assign an initial size to the vector and just push in the objects you acutally have:

std::vector<std::unique_ptr<ClassA>> object1;  //empty vector
object1.push_back(std::make_unique<ClassA>()); //now has 1 element
object1.push_back(std::make_unique<ClassA>()); //now has 2 elements

And as a last improvement, unless you really need there to be pointers in the vector (e.g. because you have polymorphic elements), just use a vector of objects, not of pointers:

std::vector<ClassA> object1; //empty vector
object1.push_back(ClassA{}); //now has 1 element
object1.push_back(ClassA{}); //now has 2 elements

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.