I need to implement a for_each
function, like below. I know std::for_each
could apply fn
to each element, but we cannot erase elements in std::for_each
. I need to extend this template function, so that in fn
, the caller can both visit elements and erase elements one at a time. Is there a proper way to do this?
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class A
{
public:
explicit A(){
mVec.clear();
}
~A(){}
template<class T> void for_each(T fn)
{
for(size_t i = 0; i < mVec.size(); ++i)
{
//fn can erase element or just visit element
fn(mVec[i]);
}
}
vector<int> mVec;
};
int main()
{
A test;
for(int i = 0; i < 8; ++i)
{
test.mVec.push_back(i);
}
test.for_each([&test](int i){
if (i % 2 == 0)
{
cout << i << " deleted" << endl;
test.mVec.erase(find(test.mVec.begin(), test.mVec.end(), i));
}
else
{
cout << i << " parse" << endl;
}
});
system("pause");
return 0;
}
Edit: In for_each
template function, we do not know whether the caller will erase elements or not. Erasing elements is done in fn