I have defined a vector which consist of pairs and vectors. For better readability, I do this
#include <iostream>
#include <vector>
using namespace std;
class foo {
public:
vector< pair<int, vector<int> > > v;
vector< pair<int, vector<int> > >::iterator it;
void bar()
{
for( it = v.begin(); it != v.end(); it++ ) {
if ( 10 == (*it).first ) {
vector<int> a = (*it).second; // NOTE
a[0] = a[0]*2; // NOTE
}
}
}
};
int main()
{
foo f;
f.bar();
return 0;
}
As you can see, I assign (*it).second to a variable a so that I manipulate easily. Problem is, when I change the value of a, the original vector v doesn’t change. I can resolve that changing a to (*it).second every where in the loop. However this will make the code hard for reading.
Is there any way to reflect the changes in a to the original v? I have to say call by reference like this
vector<int> a = &(*it).second;
doesn’t work
You need to declare
aas a reference:vector<int>& a = (*it).second;Ampersand in
std::vector<int> a = &(*it).second;is being parsed as adress-of operator andaisn’t a pointer – that’s why it doesn’t work/compile.