How to implement for_each function as C ++?

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 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_eachthe template function, we do not know whether the caller will erase or not. Erase items are executed infn

+4
source share
2 answers

bool , true " "? for_each - .

    size_t i = 0;
    for(size_t j = 0; j < mVec.size(); ++j) {
        if (!fn(mVec[j])) {
            // The element must be kept
            if (i != j)
                mVec[i] = std::move(mVec[j]);
            i++;
        }
    }
    mVec.resize(i);

, O (n), , .

EDIT: std:: remove_if(), @ChenOT .

    n = std::remove_if(mVec.begin(), mVec.end(), fn) - mVec.begin();
    mVec.resize(n);
+4

"", , - :

for (size_t i = 0; i < mVec.size(); i++) {
    if (some_condition) mVec.erase(mVec.begin() + i);
    else do_something_else;
}

, !

-3

Source: https://habr.com/ru/post/1618095/


All Articles