tariq zafar
tariq zafar

Reputation: 659

Regarding vector values

Here is a code snippet below. Input to program is

dimension d[] = {{4, 6, 7}, {1, 2, 3}, {4, 5, 6}, {10, 12, 32}};
PVecDim vecdim(new VecDim());
    for (int i=0;i<sizeof(d)/sizeof(d[0]); ++i) {
        vecdim->push_back(&d[i]);
    }
getModList(vecdim);

Program:

class dimension;
typedef shared_ptr<vector<dimension*> > PVecDim;
typedef vector<dimension*> VecDim;
typedef vector<dimension*>::iterator VecDimIter;

struct dimension {
    int height, width, length;
    dimension(int h, int w, int l) : height(h), width(w), length(l) {

    }
};

PVecDim getModList(PVecDim inList) {
        PVecDim modList(new VecDim());
        VecDimIter it;

        for(it = inList->begin(); it!=inList->end(); ++it) {
            dimension rot1((*it)->length, (*it)->width, (*it)->height);
            dimension rot2((*it)->width, (*it)->height, (*it)->length);

            cout<<"rot1 "<<rot1.height<<" "<<rot1.length<<" "<<rot1.width<<endl;
            cout<<"rot2 "<<rot2.height<<" "<<rot2.length<<" "<<rot2.width<<endl;

            modList->push_back(*it);
            modList->push_back(&rot1);
            modList->push_back(&rot2);
            for(int i=0;i < 3;++i) {
                cout<<(*modList)[i]->height<<" "<<(*modList)[i]->length<<" "<<(*modList)[i]->width<<" "<<endl;
            }
        }
            return modList;
}

What I see is that the values rot1 and rot2 actually overwrite previous values. For example that cout statement prints as below for input values defined at top. Can someone tell me why are these values being overwritten?

rot1 7 4 6
rot2 6 7 4
4 7 6 
7 4 6 
6 7 4 
rot1 3 1 2
rot2 2 3 1
4 7 6 
3 1 2 
2 3 1 

Upvotes: 0

Views: 43

Answers (1)

juanchopanza
juanchopanza

Reputation: 227418

You are storing pointers to local variables when you do this kind of thing:

modList->push_back(&rot1);

These get invalidated every loop cycle. You could save yourself a lot of trouble by not storing pointers in the first place.

Upvotes: 3

Related Questions