I need to implement a function for_eachas shown below. I know what std::for_eachcan apply fnto each element, but we cannot erase the elements in std::for_each. I need to expand this template function so that the fncaller can visit the elements at the same time and erase the elements one at a time . Is there any 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(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_eachthe template function, we do not know whether the caller will erase or not. Erase items are executed infn
source
share