Passing vector of vectors to function
Asked Answered
C

2

9

I have a function which accepts a

vector<vector<MyClass>> 

and modifies the MyClass instances. It's been a long time since I've written any C++ and I'm having difficulty remembering what is sufficient here for passing the entire arg by reference instead of by value.

My original method signature was:

void modifyVectorOfVectors(vector<vector<MyClass> > vec) { ... }

I want to make this memory efficient so I originally changed this to:

void modifyVectorOfVectors(vector<vector<MyClass*> > vec) { ... }

Then I realized that this would mean that my vec value would still make copies of all the inner vectors. So I changed my function signature to:

void modifyVectorOfVectors(vector<vector<MyClass*> >* vec) { ... }

Is this sufficient, or do I also need to do something like:

void modifyVectorOfVectors(vector<vector<MyClass*>* >* vec) { ... }

Could someone highlight the memory differences between all of these? Thanks a lot!

Crackbrained answered 25/5, 2015 at 19:55 Comment(3)
why dont you just take reference to the vector of vectors? No memory leaks that waySilvereye
Using typedef might make it clearerFirewater
if using modern c++ then a using would be even better :)Maliamalice
S
17

Simply

void modifyVectorOfVectors( vector< vector< MyClass > >& vec) { ... }
Scholasticism answered 25/5, 2015 at 20:0 Comment(0)
S
3
  1. void modifyVectorOfVectors(vector<vector<MyClass> > vec) { ... } Copy external vector which has all elements of inner vector
  2. void modifyVectorOfVectors(vector<vector<MyClass*> > vec) { ... } Copy external vector which has all inner vectors which holds all pointers of MyClass
  3. void modifyVectorOfVectors(vector<vector<MyClass*>* > vec) { ... } Copy external vector which has all pointers of inner vectors and and inner vectors holds pointers of MyClass
  4. void modifyVectorOfVectors(vector<vector<MyClass*> *> vec*) { ... } Copy pointer of external vector which has all pointers of inner vectors and and inner vectors holds pointers of MyClass
Straley answered 25/5, 2015 at 20:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.