We're a community of 1077K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,076,478 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

std::vector and for loop questions

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
5 Hours
Discussion Span
3 Years Ago
Last Updated
3
Views
yakovm
Light Poster
27 posts since May 2009
Reputation Points: 46
Solved Threads: 0
Skill Endorsements: 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.

vali82
Light Poster
32 posts since Aug 2009
Reputation Points: 12
Solved Threads: 4
Skill Endorsements: 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.

StuXYZ
Practically a Master Poster
681 posts since Nov 2008
Reputation Points: 760
Solved Threads: 138
Skill Endorsements: 0

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
 
© 2013 DaniWeb® LLC
Page rendered in 0.0558 seconds using 2.65MB