Please take a look at this example:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class mySubContainer
{
public:
string val;
};
class myMainContainer
{
public:
mySubContainer sub;
};
void doSomethingWith( myMainContainer &container )
{
container.sub.val = "I was modified";
}
int main( )
{
vector<myMainContainer> vec;
/**
* Add test data
*/
myMainContainer tempInst;
tempInst.sub.val = "foo";
vec.push_back( tempInst );
tempInst.sub.val = "bar";
vec.push_back( tempInst );
// 1000 lines of random code here
int i;
int size = vec.size( );
myMainContainer current;
for( i = 0; i < size; i ++ )
{
cout << i << ": Value before='" << vec.at( i ).sub.val << "'" << endl;
current = vec.at( i );
doSomethingWith( current );
cout << i << ": Value after='" << vec.at( i ).sub.val << "'" << endl;
}
system("pause");//i suck
}
A hell lot of code for an example, I know.
Now so you don't have to spend years thinking about what this [should] do[es]: I have a class myMainContainer
which has as its only member an instance of mySubContainer
. mySubContainer
only has a string val
as member.
So I create a vector and fill it with some sample data.
Now, what I want to do is: Iterate through the vector and make a separate function able to modify the current myMainContainer in the vector. However, the vector remains unchanged as the output tells:
0: Value before='foo'
0: Value after='foo'
1: Value before='bar'
1: Value after='bar'
- What am I doing wrong?
doSomethingWith has to return void, I can't let it return the modified myMainContainer
and then just overwrite it in the vector, that's why I tried to pass it by reference as seen in the doSomethingWith definition above.