0

Hello i have two questions
1.
I have vector that I have delete several members from it after I do it I have a problem to access other member because index if other members has changed. What is the best way to know and access the members of the vector after the deletion?
2.

for(int i = 0;i< foo();++i)
int foo()

Does foo function calculated every time that loop is initialized?
Thank you in advance

3
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by StuXYZ
0

Hi,

1)
The best way is for you NOT to depend on the order of the object in the vector;
If you ABSOLUTELY MUST depend on their order, keep pointers to object in the vector and delete the object + replace it in the vector with NULL; that is, don't delete the actual vector location, just the object in it. That will make the other object stay in the same position.

2)
Assuming you have:

int foo(){...}
    // ...
    for(int i = 0;i< foo();++i)
    {
        // some stuff
    }
    // ...

Then the foo() function will get evaluated for EVERY loop, NOT just at the initialization stage.

0

First off : The point of a vector is to know the order (otherwize use a set or list etc) .

Second : if you have a vector of pointer either :
(a) consider an autoptr/boost::shared_ptr [prefered] and just delete the element with a remove_if and then an erase e.g

std::vector<boost::shared_ptr<Obj> > Vec;
// ... populate etc
std::vector<boost::shared_ptr<Obj> >::iterator ec=
   remove_if(Vec.begin(),Vec.end(),
		boost::bind(&Vec:requiresDel,_1));
  Vec.erase(ec,Vec.end());

Now you might have a deletion that is more complex or depends on the index number. then try this:

std::vector<Obj*> Vec;
// ... populate here.
for(long int i=Vec.size()-1;i>=0;i--)
  {  
     if ( delRequied(Vec[i]) )
        {
           delete Vec[i]; 
           Vec.erase(Vec.begin()+i);
        }
  }

Note:
Normally I use size_t not long int but that has lead to confusion in the past.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.