Jump to content
  • Advertisement
Sign in to follow this  

C++: std::find and erase in vector struct

This topic is 2825 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

Hi, I have a std::vector that points to a structure, like this:

std::vector<myObjects::myObjectLib> myObject;

typedef struct {
float X,Y,Z;
int objID;
} myObjectLib ;

The myObject vector is already filled with data, and now I'd like to find and erase all the items where objID=1 (to make an example).
I know how to do it with a standard vector, but I don't know how to do it when the vector, like in this case, addresses a struct.

Share this post

Link to post
Share on other sites
In this case you wouldn't use std::find(), you'd use std::find_if(). Create a predicate that will check the objID and pass it to the function.

Share this post

Link to post
Share on other sites
I created the predicate function like this:

bool checkObj (myObjects::myObjectLib temp) {
if (temp.objID==1) return true;
else return false;

and later

std::vector<int>::const_iterator it;
it = std::find_if (myObject.begin(), myObject.end(), checkObj(myObject)); //<- how do I pass the myObject vector?

I don't know how to pass the myObject vector to the predicate. And not sure if I made some more mistakes...

Share this post

Link to post
Share on other sites
Two small things:
1. Your predicate should take a constant reference (Although in this case the compiler would probably optimise both to the same assembly), so your function signature would be:
bool checkObj (const myObjects::myObjectLib& temp)

2. You don't pass the vector to the predicate directly, find_if() does that. So your find_if() call looks like:

it = std::find_if(myObject.begin(), myObject.end(), checkObj);

Share this post

Link to post
Share on other sites
You don't have to pass it yourself, find_if will do that automatically. Also you probably should use remove_if for "removal" operations since that will reduce copy operations.

[source lang="c++"]
struct HasId {
HasId(int i) : id(i) { }
bool operator()(const myObjects::myObjectLib &obj) { return obj.objID==id; }
int id;


iterator new_end = remove_if(myObject.begin(), myObject.end(), HasId(1));
myObject.erase(new_end, myObject.end());

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

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

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!