ph03n1x ph03n1x - 16 days ago 7
C++ Question

Passing and modifying array of vectors through functions in c++

(I'm from C background and new in C++ and its STLs)

I'm writing a C++ array of vectors that will be passed (as a reference of an array of vectors) through a function and will be processed in it.

In this case [in C] I would have passed a pointer to my custom data type (call by value under the hood.)

My code that's giving errors in compile time while trying to do so:

#include <cstdio>
#include <vector>

using namespace std;

/*
the problem is I can't get the syntax. vector<type> &var is
a reference to a single dimension array of vectors.
*/

void pass_arrayOf_vect(vector<int> &array, int lmt);

int main() {

int lmt = 10;

vector<int> lst[lmt];

pass_arrayOf_vect(lst, lmt);

return 0;
}

/*
and the traditional ambiguity of whether using "." or "->" for
accessing or modifying indexes and their members.
*/

void pass_arrayOf_vect(vector<int> &lst, int lmt) {


for (int i = 0; i < lmt; i++) {

lst[i].push_back(i*i);

}


for (int i = 0; i < lmt; i++) {
printf("array[%d]: ", i);
for (int j = 0; j < lst[i].size(); j++) {

printf("%d ",lst[i][j]);
}
printf("\n");
}

printf("\n");

return;
}

Answer

In the main function the lst variable is an array of vectors. When you pass this to the pass_arrayOf_vect function you pass a pointer to the first element.

I.e. when you do

pass_arrayOf_vect(lst, lmt);

it's actually the same as doing

pass_arrayOf_vect(&lst[0], lmt);

So the function you call needs to accept a pointer to a vector as its first argument (not a reference):

void pass_arrayOf_vect(vector<int> *array, int lmt);
//                                 ^
// Note use of asterisk instead of ampersand

An even better solution would be to use an std::array of vectors instead. Or if you're on an older compiler without support for std::array, or need the amount to be run-time configurable (in which case you can't use plain C-style arrays anyway), use a vector of vectors.