erase-remove usage

W

Wing

Hello,

I have the following code:

////////////////////////////

class Obj
{
public:
int time;
string str;
};

vector<Obj> array;

////////////////////////

I would like to remove all the "Obj" objects where their "time"
variables are less than or equal to, say x. Could anyone teach me how
to use erase-remove to do that?

Thank you so much!
 
I

Ian Collins

Wing said:
Hello,

I have the following code:

////////////////////////////

class Obj
{
public:
int time;
string str;
};

vector<Obj> array;

////////////////////////

I would like to remove all the "Obj" objects where their "time"
variables are less than or equal to, say x. Could anyone teach me how
to use erase-remove to do that?
Read up on std::vector.remove_if(). a google for "vector remove_if"
will find you some examples.
 
W

Wing

Hello,

I have googled for this topic. However, all the examples I saw are
based on vector<int>.

I think that I need to add some extra functions into my code in order
to do what I want. Anyone can give me some pointer? I am very
confused.... :(

Thank you.
 
I

Ian Collins

Wing wrote:

Please don't top post.
Hello,

I have googled for this topic. However, all the examples I saw are
based on vector<int>.
Probably because it's the most straightforward case!
I think that I need to add some extra functions into my code in order
to do what I want. Anyone can give me some pointer? I am very
confused.... :(

Extending your Obj to give an example:

#include <vector>
#include <functional>
#include <string>
#include <iostream>
#include <algorithm>
#include <iterator>

struct Obj
{
int time;
std::string str;
Obj( int time ) : time(time) {}
friend std::eek:stream& operator<<( std::eek:stream& out, const Obj& o ){
return out << o.time;
}
};

struct RemoveAfter : std::unary_function<Obj, bool>
{
bool operator()(const Obj& x){ return x.time > 10; }
};

int main() {
std::vector<Obj> array;

array.push_back( Obj( 5 ) );
array.push_back( Obj( 15 ) );
array.push_back( Obj( 10 ) );

std::copy(array.begin(),
array.end(),
std::eek:stream_iterator<Obj>(std::cout," "));
std::cout << std::endl;

std::vector<Obj>::iterator last = std::remove_if( array.begin(),
array.end(),
RemoveAfter() );
std::copy(array.begin(),
last,
std::eek:stream_iterator<Obj>(std::cout," "));
std::cout << std::endl;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,043
Latest member
CannalabsCBDReview

Latest Threads

Top