Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

Laroche

std::vectors

This topic is 5807 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

How would I first check if a given pointer (boost shared_ptr) is in a vector, then remove it? the code to do it that I have is
void CGame::RemoveVisibleEntity(entity_ptr pEntity)
{
	for (std::vector::iterator p = VisibleEntityVector.begin(); p != VisibleEntityVector.end(); ++p)
	{
		if (pEntity == (*p))
		{
			VisibleEntityVector.erase((p));
			return;
		}
	}	
	return;
}
 
If anyone could post example code showing how check if a pointer is in a vector, and if not, add it in, I would be really grateful.

Share this post


Link to post
Share on other sites
Advertisement
That seems to work well enough in most cases, howver occasionally it fails. Could this be because the pointer == v.end()? is there any way to check?

Share this post


Link to post
Share on other sites
Not with inserting, but with removing it fails..let me show some code:


void CGame::RemoveEntity(entity_ptr pEntity)
{
if (std::find(EntityVector.begin(), EntityVector.end(), pEntity) == EntityVector.end())
{
EntityVector.erase(EntityVector.end());
}
}


I''m not really sure if this is proper way to do it, I had just adapted it from the previous answer. It works most of the time, but occasionaly one bullet or particle or whatever will just not go away. I followed it for a while and it just...doesn''t remove itself.

Share this post


Link to post
Share on other sites
Ah. Since you're using a shared_ptr, it is easy :


    
#include<vector>
#include<algorithm>

v.erase( std::remove( v.begin(), v.end(), ptr ), v.end() );


Known as the erase-remove idiom.
Note that with a regular ptr, you'd have a memory leak.

Documents [ GDNet | MSDN | STL | OpenGL | Formats | RTFM | Asking Smart Questions ]
C++ Stuff [ MinGW | Loki | SDL | Boost. | STLport | FLTK | ACCU Recommended Books ]


[edited by - Fruny on June 30, 2002 9:08:39 PM]

Share this post


Link to post
Share on other sites
Just tried it, and get the following error message:

cannot convert parameter 2 from ''const class boost::shared_ptr *(void) const'' to ''class boost::shared_ptr *''
Context does not allow for disambiguation of overloaded function

Again, I''ll show you the code:^


void CGame::RemoveVisibleEntity(entity_ptr pEntity)
{
VisibleEntityVector.erase( std::remove( VisibleEntityVector.begin(),
VisibleEntityVector.end(), pEntity ), VisibleEntityVector.end );
}

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!