Reputation: 21
How to erase all values from vector of struct, where struct value k equals to 0?
struct tabuRecord {
int x;
int y;
int k;
tabuRecord( int x, int y, int k)
: x(x), y(y), k(k){}
};
vector <tabuRecord> tabu;
v.insert(v.begin(), tabuRecord(1, 2, 3));
v.insert(v.begin(), tabuRecord(4, 5, 0));
v.insert(v.begin(), tabuRecord(7, 8, 9));
v.insert(v.begin(), tabuRecord(10, 11, 0));
I have tried to
tabu.erase(std::remove(tabu.begin(), tabu.end(), tabu.k=0), tabu.end());
and
tabu.erase(std::remove(tabu.begin(), tabu.end(), tabuRecord.k=0), tabu.end());
Upvotes: 0
Views: 309
Reputation: 16876
Try something like this:
tabu.erase(
std::remove_if(tabu.begin(), tabu.end(), [valueToErase](const tabuRecord & t) {
return (t.x==valueToErase.x) && (t.y == valueToErase.y) && (t.k == valueToErase.k);
}), tabu.end());
This uses a lambda that returns true
if the three fields are equal, and it removes all values where this is the case.
Here's a full example:
#include <vector>
#include <algorithm>
#include <iostream>
int main(int argc, char **argv)
{
tabuRecord valueToErase(1, 2, 3); // example value to remove
tabu.push_back({ 1, 2, 3 });
tabu.push_back({ 4, 5, 6 });
tabu.push_back({ 1, 2, 3 });
tabu.push_back({ 7, 8, 9 });
tabu.erase(
std::remove_if(tabu.begin(), tabu.end(), [valueToErase](const tabuRecord & t) {
return (t.x==valueToErase.x) && (t.y == valueToErase.y) && (t.k ==
valueToErase.k);
}), tabu.end());
for (tabuRecord t : tabu) {
std::cout << "x: " << t.x << " y: " << t.y << " k: " << t.k << std::endl;
} // print all entries to verify that the correct ones were removed
return 0;
}
Also, there's an error in your construtor, you probably wanted this instead of setting all fields to the same value:
: x(x), y(y), k(k) {}
Upvotes: 3
Reputation: 12968
std::remove
needs a tabuRecord
to match against, so you need to do something like.
tabuRecord value_to_remove(1,2,3);
tabu.erase(std::remove(tabu.begin(), tabu.end(), value_to_remove), tabu.end());
If you want to remove only based on the k
member, you need to use std::remove_if
and pass an appropriate function to match for it.
auto match_func = [](const tabuRecord& obj) { return obj.k == 2; };
tabu.erase(std::remove_if(tabu.begin(), tabu.end(), match_func), tabu.end());
Upvotes: 4
Reputation: 22023
I guess what you want to do is to remove all objects that have k==0
, so create a lambda for that:
tabu.erase(
std::remove_if(tabu.begin(), tabu.end(),[](const tabuRecord& t){return t.k == 0;}),
tabu.end());
std::remove
cannot work because it's not one value that you want to remove, but all values with a specific pattern, which is what std::remove_if
does.
Upvotes: 6