This question showed how to use erase/remove_if based on vector indices using a function predicate. This works well the first time the function is called but because the local static variable maintains state, on the next call to a different vector I'd be out of luck. So I thought I could use a functor with a private variable that would be re-usable. It mostly works except for the first element. There's something specific to the way remove_if uses the functor that messes up initialization of the private variable
#include <vector>
#include <algorithm>
#include <iostream>
#include <iterator>
using namespace std;
class is_IndexEven_Functor {
public:
is_IndexEven_Functor() : k(0) {}
bool operator()(const int &i) {
cout << "DEBUG: isIndexEvenFunctor: k " << k << "\ti " << i << endl; ////
if(k++ % 2 == 0) {
return true;
} else {
return false;
}
}
private:
int k;
};
int main() {
is_IndexEven_Functor a;
a(0);
a(1);
a(2);
a(3);
vector<int> v;
v.push_back(0);
v.push_back(1);
v.push_back(2);
v.push_back(3);
cout << "\nBefore\n";
copy(v.begin(), v.end(), ostream_iterator<int>(cout, " ")); cout << endl;
is_IndexEven_Functor b;
v.erase( remove_if(v.begin(), v.end(), b), v.end() );
cout << "\nAfter\n";
copy(v.begin(), v.end(), ostream_iterator<int>(cout, " ")); cout << endl;
return 0;
}
Here's the output:
DEBUG: isIndexEvenFunctor: k 0 i 0
DEBUG: isIndexEvenFunctor: k 1 i 1
DEBUG: isIndexEvenFunctor: k 2 i 2
DEBUG: isIndexEvenFunctor: k 3 i 3
Before
0 1 2 3
DEBUG: isIndexEvenFunctor: k 0 i 0
DEBUG: isIndexEvenFunctor: k 0 i 1 // why is k == 0 here ???
DEBUG: isIndexEvenFunctor: k 1 i 2
DEBUG: isIndexEvenFunctor: k 2 i 3
After
2
The crux of the question is why is the value of k
equal to 0 on the second call to the functor (and how do I fix it)?
I'm guessing this has something to do with remove_if using it as temporary object or something but I don't really understand what that means.
EDIT: it would be great if I could avoid c++11