1,105,375 Community Members

std::vector and for loop questions

Member Avatar
yakovm
Light Poster
27 posts since May 2009
Reputation Points: 36 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
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

Member Avatar
vali82
Light Poster
32 posts since Aug 2009
Reputation Points: 1 [?]
Q&As Helped to Solve: 4 [?]
Skill Endorsements: 0 [?]
 
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.

Member Avatar
StuXYZ
Practically a Master Poster
691 posts since Nov 2008
Reputation Points: 688 [?]
Q&As Helped to Solve: 140 [?]
Skill Endorsements: 1 [?]
 
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.

You
This article has been dead for over three months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article