NIKHIL
NIKHIL

Reputation: 13

How to pass static vector of vectors by reference?

I want to pass v vector such that it does not get copied every time when I call the function one(..). But I am not able to do that.

Can anyone help me to get out from this?

int n; // global variable
void one(vector <int >(&v)[n]) 
{
    v[0][0] = 1;
}

int main()
{
    cin >> n;//n=1
    vector <int > v[n];
    v[0].push_back(9);
    one(v);
    cout << v[0][0];
}

The error message:

prog.cpp:5:32: error: variable or field ‘one’ declared void
  void one(vector <int > (&v)[n]){
                                ^
prog.cpp:5:27: error: ‘v’ was not declared in this scope
  void one(vector <int > (&v)[n]){
                           ^
prog.cpp: In function ‘int main()’:
prog.cpp:17:6: error: ‘one’ was not declared in this scope
 one(v);
      ^

Upvotes: 1

Views: 671

Answers (1)

JeJo
JeJo

Reputation: 32942

First of all, you do not have vector of vectors which will look like std::vector<std::vector<Type>>. What you have is a variable-length array of vectors.

VLA's are not part of C++ standard, rather they are compiler-extensions. See this post for more information: Why aren't variable-length arrays part of the C++ standard?

That being said, if n was compile-time know, you could solve the issue by providing n as a non-type template parameter.

template<std::size_t n>
void one(std::vector<int> (&v)[n])
{
    v[0][0]=1;
}

In the case of vector of vectors, there is no need for templates, rather pass it by reference.

void one(std::vector<std::vector<int>> &v)
//                               ^^^^^^^^^^
{
    v[0][0]=1;
}

Upvotes: 1

Related Questions