[C++] Remove algorithm with a vector of a struct
I have a struct of a few integers, and I have a vector of those structs, and I have been able to use that in my code, however I have come to a point where the STL remove algorithm would improve the efficiency of my code but I'm unsure of what the last argument should be.
Posted Apr 8, 2012, 4:22 AM UTC
54
The last argument would be a copy of the struct you want to remove. Suppose you wanted to remove all elements of the vector where x=2, y=5, and l=6. You would do this.
This requires knowing in advanced exactly how the whole struct looks before you are able to remove it. Suppose you wanted to remove any struct which matches just one variable. For example, remove any struct where x = 5. This would require a bit more logic. I don't believe it's possible to do with std::remove. You would have to iterate over your vector and check the values.
This is wrong. This code:
simply will not compile. To use remove() the type being removed must support operator==(), and the user's struct does not do so. This code will compile and uses remove correctly:
remove_if covers the second use case you mentioned. It probably does something similar, but I reckon it's probably usually going to be better to just use the officially supplied implementation.
Thank you so much! Although the second part was more or less what I was using as an alternative.