Reputation:
Hello I'm trying to access an element of a vector containing a bunch of class objects and delete only one of the objects from the vector.
The problem is I don't understand vectors and I can't find any information online which is helpful.
My code:
void MyExperiment::deselectSingle() {
Ogre::Vector3 vNewPos = mPickedObj->_getDerivedPosition();
mPickedObj->showBoundingBox( false );
mMoveThis->removeChild( mPickedObj->getName() );
mSceneMgr->getRootSceneNode()->addChild( mPickedObj );
mPickedObj->_setDerivedPosition( vNewPos );
for ( Ogre::SceneNode* it = vObjects.begin(); it < vObjects.end(); it++ ) {
static std::string objNameStr;
objNameStr = vObjects.at( *it )->getName();
if ( objNameStr == mPickedObj->getName() )
{
vObjects.erase( *it );
break;
}
}
if ( mMoveThis->numAttachedObjects() == 0 ) bSelected = false;
return;
}
I know this code won't work. I've read some stuff online about how to use iterators however when I try some of the things suggested errors crop up. In fact what I have here causes a few errors.
My plan for this function was to iterate through the vObjects vector which contains Ogre::SceneNode pointer elements. If one of the elements matches the mPickedObj's name then I want to remove it from the vector by the .erase() foo. The code above does not work, it was just there as an example though it is what I tried in my application.
Upvotes: 0
Views: 101
Reputation: 4245
you are initializing the vector in rightway before forloop; but in initialization part of for loop: why reinitialized it again?
Ogre::SceneNode* it = vObjects.begin()
Iterator 'll be initialized to begin() [first element] and loops through its item until it reaches end.
(it=vObjects.begin();it!=vObjects.end();it++)
you should not compare it normally with ' < ' operator. it ends when it reaches end [i.e end position exclusive]
i'm not sure what is vObjects.erase(*it) ...
But if you want to dereference an element in vector do
vector[i] //if ith element already present if not it causes segmentation fault [can use it like normal array]
vector.at(i) //safe and if doesn't exist throws exception
for deleting an element you pass the iterator position for erase(it) to delete it; if element is at last can use pop_back().
Upvotes: 0
Reputation: 52689
A beginner's tutorial on vectors
Not too hard at all - take the time to understand the STL collections, and you'll have a resource that fits for 80% of the things you need in the future.
The only 'special' thing you need to know for a vector, as opposed to the other collections, is that erasing an element in the middle of a vector will cause the rest of the elements to move down to close the gap you just made.
Upvotes: 1