How to pass vector< int > v[n] as parameter in function?

Hello guys, please help me in this query
I want to pass vector<int> arr[N] as parameter to a function,

I found one way on internet , i. e void function(vector<int> arr[]){}

are there any better ways than this like passing by reference ?

U can pass vector < vector < int > > arr
i.e vector of vectors instead of array of vectors

if u don’t want to modify original :
void solve(vector < vector < int > > a )
else:
void solve(vector < vector < int > > &a )

2 Likes

I’m getting following error when I did that
could not convert ‘(std::vector<long long int>*)(& arr)’ from ‘std::vector<long long int>*’ to ‘std::vector<std::vector<long long int> >’ ans += calcSol(arr);

Show me the code

Share your code once, because it’s difficult to say why you are getting error without knowing what you are doing?

If you are passing a single dimensional vector then you have to pass it like
void func_name(vector < data type > a).

I cannot show code as it’s part of ongoing contest but here is something similar
its implementation of m-ary tree, each node of arr stores a vector of children.

bool func(vector<int> arr[])
{
//do operation here
}

void main()
{
   int N;
   cin >> N;
   vector<int> arr[N];
  int temp;
   for(int i=1; i<N;i++)
{
      cin >> temp;
      arr[temp].push_back(i);
}

cout << func(arr) << "\n";

look my last comment

are u trying to create a graph or something cause if that’s the case just declare the vector globally and use it where ever you want … such as below

vector<int> arr[100005]; // declared globally 
bool func()
{
//do operation here
}

void main()
{
   int N;
   cin >> N;
  int temp;
   for(int i=1; i<N;i++)
{
      cin >> temp;
      arr[temp].push_back(i);
}

cout << func(arr) << "\n";

Thanks, it helps
Is there any effiecient way to make graph than this? I think its variable size is costly.

you can clear the graph to use it again…
use

vector<int> arr[100005]; // declared globally 
bool func()
{
//do operation here
}

void main()
{
   int N;
   cin >> N;
  int temp;
   for(int i=1; i<N;i++)
{
      cin >> temp;
      arr[temp].push_back(i);
}

cout << func(arr) << "\n";
arr.clear() // clear graph from memory

this should work fine
This is pass by reference only. Don’t add & before v now.
You need to worry about by value or by reference only when its a single object/vector. But now it is an array of vectors and hence it will always be pass by reference.

1 Like