Reputation: 31
I am currently trying to work with a vector of strings, and need to be able to efficiently remove elements that are not of a certain string length.
I was thinking about doing something like vector.erase(remove_if(etc))
, however I can't use lambdas due to using C++98, and if I were to create a predicate it would need parameters because the length is a variable and can change based on user input.
Can anyone provide a basic solution to this with these restrictions?
Upvotes: 0
Views: 160
Reputation: 126797
It's not like in C++03 you didn't have functors, they were just 10x more awkward to use...
// important: outside from any function
// (local types weren't allowed as template parameters)
struct size_mismatcher {
size_t size;
size_mismatcher(size_t size) : size(size) {}
bool operator()(const std::string& s) { return s.size() != size; }
};
// in your function:
vec.erase(std::remove_if(vec.begin(), vec.end(),
size_mismatcher(target_size)),
vec.end());
Or just do it the classic way:
size_t wp = 0;
for(size_t rp = 0, n = vec.size(); rp != n; ++rp) {
if(vec[rp].size() == target_size) {
vec[wp] = vec[rp];
++wp;
}
}
vec.resize(wp);
Upvotes: 3