Reputation: 30615
If I have a std::vector and at some point through the code I add an instance of a MyClass object, later on how can I remove THAT particular object from the vector?
(I found a question on SO which explained how to remove ints, but they are primitive and I dont know if the same technique would work with user-defined classes)
std::vector<MyClass> v;
MyClass m;
v.push_back(m);
.
.
.
//Wish to remove m from v??
EDIT: You do not know the position of m in the vector.
Upvotes: 0
Views: 1314
Reputation: 16148
if you know it is still the last element:
v.pop_back();
Else
auto it=std::find(begin(v),end(v),m);
if(it!=end(v)) v.erase(it);
Note, that push_back
duplicates m
via it's copy ctor, it is not the same m
as in the code that calls push_back
it just has the same value (unlike say Java semantics).
EDIT:
op==
and op<
can be implemented like so.
struct s {
std::string name;
int id;
};
bool operator==(const s& l, const s& r) {
return l.id == r.id
&& l.name == r.name
;
}
bool operator<(const s& l, const s& r) {
return std::make_tuple(l.id, l.name)
< std::make_tuple(r.id, r.name)
;
}
Upvotes: 3
Reputation: 9474
C++11:
std::vector<int> v = {1,2,3,4,5};
auto end = std::remove(v.begin(), v.end(), 3);
v.resize(end - v.begin());
Upvotes: 0
Reputation: 227390
You have to be aware that the vector stores its own copy of m
. So you need to define a criteria for something that is equivalent to m
. Then you can use std::find
or std::find_if
to get an iterator to the first equivalent instance, and call std::vector::erase
to remove it.
Assuming equivalenve is defined via an operator==(const MyClass&, const MyClass&)
, then
auto it = std::find(v.begin(), v.end(), m);
if(it != v.end())
v.erase(it);
To use other criteria:
bool eq(const MyClass& lhs, const MyClass& rhs) { .... }
auto it = std::find_if(v.begin(), v.end(), eq);
if(it != v.end())
v.erase(it);
Here, eq
could be replaced by a functor instance or a lambda expression.
Upvotes: 2