i 'm pretty new to c++, can you help me with pointers ? i have a struct

struct Slice
{
    Slice(): {}
    SliceObj *slObj;
};

and vector:

std::vector<Slice> slices;

So on mouce touch i want to take this object to change his public var:

for (vector<Slice>::iterator it = slices.begin(); it != slices.end(); ++it) {

            Slice slice0 = slices[0];
            SliceObj *slObj = slice0.slObj;
            slObj->drag(slObj, x, y);
}

enter image description here

And of coure of course when in drag method i make : slObj->rect.x = x+0.1;, it doesn't make anything good.

Please, help me with this, i can't understand how to carefully get obj with * from another object from vector and then carefully change it's param; Trouble is in "how to carefully get SliceObj from slice0", not address of var, but this instance. So here i need to get slObj param, that in future i can make slObj.rect.x = 1;

UPDATE: when i make slObj->drag method i always see only strange number like: enter image description here but then, when glutPostRedisplay called and it's redraw on method

void SliceObj::draw(SliceObj *slObj)

then it's all good! enter image description here

有帮助吗?

解决方案

You should access the element through the iterator:

for (vector<Slice>::iterator it = slices.begin(); it != slices.end(); ++it) {

        Slice& slice0 = *it //Get the element using iterator (Note the reference, is to avoid copy)
        SliceObj *slObj = slice0.slObj;
        slObj->drag(slObj, x, y);
}

However, if you have a C++11 capable compiler, you could simplify things using range-based for loop:

for( auto& slObj : slices )
{
    liceObj *slObj = slice0.slObj;
    slObj->drag(slObj, x, y);
}

其他提示

You need to use the iterator to get the element from the vector. Here you are always getting the first element. Try this:

for (vector<Slice>::iterator it = slices.begin(); it != slices.end(); ++it) {

            Slice slice0 = *it //Get the element using iterator
            SliceObj *slObj = slice0.slObj;
            slObj->drag(slObj, x, y);
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top