Wing wrote:
Please don't top post.
Ian Collins wrote:
>>Wing wrote:
>>>Hello,
I have the following code:
////////////////////////////
class Obj
{
public:
int time;
string str;
};
vector<Objarray;
////////////////////////
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.
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::ostream& operator<<( std::ostream& 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<Objarray;
array.push_back( Obj( 5 ) );
array.push_back( Obj( 15 ) );
array.push_back( Obj( 10 ) );
std::copy(array.begin(),
array.end(),
std::ostream_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::ostream_iterator<Obj>(std::cout," "));
std::cout << std::endl;
}
--
Ian Collins.