Sign in to follow this  

Need help cleaning up this vector code

Recommended Posts

Just wondering how I should refactor this messy bit of code I just wrote. I think it does what I want it to but I can't seem to picture how to make it any neater or readable... I figure that most of the time if I use break outside of a switch then there's probably a problem somewhere ^_^ What I want to do is: I have a vector sorting in descending order. If there are any objects in the vector then I want to check an attribute of the last object (the attribute the vector is sorted by) and compare it to something else. Then I do some irrelevant stuff based on the object and pop that object off the back of the vector. Now, it may happen that more than one object also needs to be dealt with so I want to check the next object (the one before the last since this is working from the back) and keep checking until 1 turns out not to be relevant at which point I can stop since it's sorted and no earlier element could possibly be relevant. So check the last object if it exists, pop it if necessary, check the next one if it exists, pop if necessary and end the loop if I encounter an object that doesn't need attention. So far I have the rather sloppy (in pseudocode):
//Don't try to check condition on non-existent object
if( vector.size() > 0 )
		while( condition )
			rIt++; //Move to next object (reverse iterator)
			vector.pop_back(); //Delete current object
			if( vector.size() <= 0 ) //Prevent checking condition on non-existent object

I have the suspicion that this is rather messy and could be solved with smarter use of while but I really can't see how exactly. I need to keep going while there are objects in the vector and while those objects meet the condition and need to avoid dereferencing an iterator pointing to nothing.

Share this post

Link to post
Share on other sites
Oh yeah... I'd thought about that but I forgot that if the first part of an && statement evaluates to false then the second isn't even tested. I figured the second would cause a problem and it wouldn't work.

Cool, thanks.

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this