C ++ vector pointer / reference problem

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

}

Hell, code for an example, I know.

Now you don’t need to think for many years about what this [should] [es]: I have a class myMainContainerthat has an instance as its only member mySubContainer. mySubContaineronly has a string valas a member.

So, I create a vector and fill it with some data samples.

Now what I want to do is: Iterate through the vector and create a separate function that can change the current myMainContainer in the vector. However, the vector remains unchanged as the message is displayed:

0: Value before='foo'
0: Value after='foo'
1: Value before='bar'
1: Value after='bar'
  • What am I doing wrong?

doSomethingWith void, myMainContainer, , , doSomethingWith .

+5
4

:

current = vec.at( i );

current, vec.at(i).

, .

doSomethingWith(vec[i]);  // or vec.at(i) for checked access.
+11

, , ;

myMainContainer &current = vec[ i ];
doSomethingWith( current );

, , .

+2
current = vec.at(i);
doSomethingWith(current);

:

doSomethingWith(vec.at(i));
+1

If I understand correctly what is happening is that the vector will store copies of your data, not the data directly. I wonder if the proposed answers will be really useful, since a copy of the data will be made in any case. To make changes to the data, I think you need to do the following. 1. Store the pointer to the object instead of the object directly. 2. Use pointers to get an object and make changes to the data with a pointer

I think this will solve problems with ur.

0
source

All Articles