1

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);
      ^
JeJo
  • 30,635
  • 6
  • 49
  • 88
NIKHIL
  • 9
  • 1
  • 4
    You don't really have a vector of vectors. That would be spelled `std::vector>`. – StoryTeller - Unslander Monica Jul 07 '19 at 07:56
  • 2
    What you have is an array of vectors (but beware that [variable-length arrays](https://en.wikipedia.org/wiki/Variable-length_array) are not really part of C++). Why not pass it as one normally passes arrays, using pointers (as in `vector* v`) together with the length of the array? Or indeed an actual vector of vectors? – Some programmer dude Jul 07 '19 at 07:58

1 Answers1

1

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;
}
JeJo
  • 30,635
  • 6
  • 49
  • 88