# Doubt with vectors

I am having doubt with the following code. Here I have a vector of vectors wall . I have made some changes into it v[i]=v[i]+v[i-1] . But when I print wall, i get unchanged output…HELP ME.

#include <bits/stdc++.h>
using namespace std;

int main() {

``````vector<vector<int>> wall={{7, 1, 2}, {3, 5, 1, 1}, {10}};

for (auto v : wall)
{
for (int i=1;i<v.size();i++)
{
v[i]=v[i]+v[i-1];

//cout<<v[i]<<" ";

}
// cout<<endl;
}

for (auto v : wall)
{
for (int i=0;i<v.size();i++)
{

cout<<v[i]<<" ";
}
cout<<endl;
}

return 0;
``````

}

Output:
7 1 2
3 5 1 1
10

Output I expect:
7 8 10
3 8 9 10
10

I am not sure, but aren’t you supposed to use `for(auto &v: wall)` instead of `for(auto v: wall)`?

Working Code
``````#include <bits/stdc++.h>
using namespace std;

int main() {

vector<vector<int>> wall={{7, 1, 2}, {3, 5, 1, 1}, {10}};

for (auto &v : wall)
{
for (int i=1;i<v.size();i++)
{
v[i]=v[i]+v[i-1];

//cout<<v[i]<<" ";

}
// cout<<endl;
}

for (auto v : wall)
{
for (int i=0;i<v.size();i++)
{

cout<<v[i]<<" ";
}
cout<<endl;
}

return 0;
}
``````
2 Likes

It is running fine…But can you please tell me the reason why we should put ‘&’ here…as we are not making a copy here , we are just iterating…

What you are asking is out of my knowledge. But the same question was asked here, it has answers.

Here is some explanation:

Thank you suman, this was helpful

Thank you kanchan, this was helpful

This part will help!

# Modifying the elements in the container

If we want to modify the elements in a container using range-based `for`, the above `for (auto elem : container)` and `for (const auto& elem : container)` syntaxes are wrong.

In fact, in the former case, `elem` stores a copy of the original element, so modifications done to it are just lost and not stored persistently in the container, e.g.:

``````vector<int> v = {1, 3, 5, 7, 9};
for (auto x : v)  // <-- capture by value (copy)
x *= 10;      // <-- a local temporary copy ("x") is modified,
//     *not* the original vector element.

for (auto x : v)
cout << x << ' ';
``````

The output is just the initial sequence:

``````1 3 5 7 9
``````

Instead, an attempt of using `for (const auto& x : v)` just fails to compile.

g++ outputs an error message something like this:

``````TestRangeFor.cpp:138:11: error: assignment of read-only reference 'x'
``````
``````      x *= 10;
^
``````

The correct approach in this case is capturing by non-`const` reference:

``````vector<int> v = {1, 3, 5, 7, 9};
for (auto& x : v)
x *= 10;

for (auto x : v)
cout << x << ' ';
``````

The output is (as expected):

``````10 30 50 70 90
``````