Best way to pass a of vector<class> to a method of another class

I need your help:
My questions are related to my program can be as fast as possible.

I have :
1.- I create n instances of class1.
2.- vector to save this instances :
First question what is better to save pointers or reference - copies ?

3.- I want to pass this vector to a function of class2
Second question what is better to pass pointer to vector or reference.

4.- In this new function I'm going to create a vector of a new class
vector<class3> and I know the exact number of elements I have to create for this vector.

5.- I'm going to pass the instances of class1 that I've received to this vector, trought a method. So I have for class3 a method called set_class1.
Third question what is better to pass to this set_class1 pointer or reference, taking into account that I have received the class1 objects using a vector.

The code I have now : (pseudocode )


Code in main:

1
2
3
4
5
6
vector<My_class1> * v_my_class1 = new vector<My_class1>;
 for (int i=0;i<limit;i++)
 {My_class1 a_class1 = new My_class1;
  v_my_class1->push_back(*a_class1);}

  My_class2(v_my_class1) ;


1
2
3
4
5
6
My_class2(vector<My_class1> * a_vector_of_class1)

  vector<class3> v_vector_class3 ;
  for (int i=0;i<a_vector_of_class1->size();i++)
  v_vector_class3.push_back (*(new class3));
  v_vector_class3[i].set_class1(&a_vector_of_class1->at(i) 


( a_vector_of_class1->at(i) compile a_vector_of_class1[i] not ... ???)


Any advise ? Thanks
Last edited on
If you want your program to be as fast as possible, don't dynamically allocate your vector. There is no need - the actual contents of the vector are stored in dynamically allocated memory behind the scenes anyway.

Also, when you push entries onto to a vector<My_class1>, I believe they are copied into the vector's memory, so dynamically allocating your copy will just make things slower.

As for passing by pointer or by reference, the overhead should be about the same (and for a large object, both should be much better than passing by value). I would use references where possible, rather than pointers. Note that if a function isn't going to change a reference passed to it then you should make it a const reference to make the function more versatile.
Topic archived. No new replies allowed.