mehdi
mehdi

Reputation: 686

is there better or correct way to use objects with vector in c++?

i have a class like this:

class Foo{
public:
   Foo(); 
   Foo(int, int, int)
  ~Foo();
private:    
   int a;
   int b;
   int c;
}

and int main function and like to save my elements(objects) in a vector:

int main()
{
   vector <Foo*> foo; // <------this line
   for(int i=0; i<=500; i++){
   foo.push_back(new Foo(i+1,i+2; i+3)); //<------ this line 
}

is there a better solution to do that and replace 2 line above?

tnx all;

Upvotes: 1

Views: 68

Answers (1)

molbdnilo
molbdnilo

Reputation: 66459

You need to unlearn that Java thing where you write "new" all the time just to create an object.

int main()
{
   vector<Foo> foo;
   for(int i=0; i<=500; i++)
       foo.push_back(Foo(i+1, i+2, i+3));
}

or, in C++11,

int main()
{
   vector<Foo> foo;
   for(int i=0; i<=500; i++)
       foo.emplace_back(i+1, i+2, i+3);
}

Upvotes: 4

Related Questions