[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.

Example

Posted Apr 8, 2012, 4:22 AM UTC

54
Darkhack•

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.

s d;
d.x = 2;
d.y = 5;
d.l = 6;
remove( v.begin(), v.end(), d);

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.

for (vector<s>::iterator it=v.begin() ; it < v.end(); it++ ) {
    if(it->x == 5)
        v.erase(it);
}
1
[deleted]•

This is wrong. This code:

 remove( v.begin(), v.end(), d);

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:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

struct s {
     s( int ax, int ay, int al ) : x(ax), y(ay), l(al) {}
     int x,y,l; //struct of 3 integers
     
};

bool operator==( const s & s1, const s & s2 ) {
    return s1.x == s2.x && s1.y == s2.y && s1.l == s2.l;
}

void Print( const vector <s> & v ) {
    for( unsigned int i = 0; i < v.size(); i++ ) {
        cout << "[" << v[i].x << "," << v[i].y << "," <<v[i].l << "]\n";
    }
    cout << "\n";
}

int main(){

    vector<s> v; //vector of struct s
    v.push_back( s( 1, 2, 3 ) );
    v.push_back( s( 1, 0, 3 ) );
    v.push_back( s( 1, 2, 4 ) );
    Print( v );
    remove( v.begin(), v.end(), s(1, 0, 3 )); 
    Print( v );
}
3
eOgas•

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.

2
TreehamOP•

Thank you so much! Although the second part was more or less what I was using as an alternative.

1