PDA

View Full Version : Best way to pass a of vector<class> to a method of another class



tonnot
29th June 2011, 09:49
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:


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) ;


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

mcosta
29th June 2011, 09:53
( a_vector_of_class1->at(i) compile a_vector_of_class1[i] not ... ???)

try with

(*a_vector_of_class1)[i]

SixDegrees
2nd July 2011, 01:02
There is no difference in performance between passing pointers or references; they are, in fact, identical operations when compiled. Passing by reference is syntactically "cleaner" than passing by pointer, since you don't have to explicitly dereference the object, but you aren't going to see any improvement in execution speed either way.

Have you considered taking an introductory course in C++, or programming in general? You are spending a huge amount of time here pursuing very basic concepts, and in many cases they don't seem to be sinking in. You are going to wind up with a patchwork, imperfect understanding of a limited subset of programming/C++/Qt that will do you more harm than good in the long run.