-2

I want to store some int vectors into a vector, so firstly I initialize a vector type vector, then iterate for begin to end, and store int numbers into each subvectoer from 0 to 4 like below code:

std::vector<std::vector<int>  > v(12);

void fun_1(std::vector<int> a )
{
    for (int i = 0; i < 5; ++i)
    {
        a.push_back(i);
    }
}
int main()
{

    for (int i = 0; i < 12; ++i)
    {
        fun_1(v[i]);
    }

    cout<<v[0].at(2);
}

So after I done that, there is always a segmentation fault which I think is because subvector is still empty, they are not assigned, so I am wondering how can I modify this to reach my goal? Thank for any idea.

MMzztx
  • 243
  • 5
  • 15

3 Answers3

0

Function fun_1 accepts its input parameter by copy so it only modifies the local copy of the vector, not the original one passed in. So the original one remains empty. Once you attempt to access one of its (non-existent) elements, it throws an exception.

If you change fun_1 to accept its argument by reference:

void fun_1(std::vector<int>& a )

This should work just fine.

Argenet
  • 379
  • 2
  • 9
0

You send parameter to your function by copy , you should send this by reference:

void fun_1(std::vector<int> &a )
{
    for (int i = 0; i < 5; ++i)
    {
        a.push_back(i);
    }
}
Morteza Jalambadani
  • 2,190
  • 6
  • 21
  • 35
0

You are currently passing the vector by value in fun_1, so once you return, all of the changes you made to a are discarded. fun_1 should look something like

void fun_1(std::vector<int> &a )
{
   for (int i = 0; i < 5; ++i)
   {
      a.push_back(i);
   }
}

This will cause the call to fun_1 in main to actually manipulate v, instead of manipulating a copy of v.

Trevor
  • 366
  • 2
  • 11