Tech Off Post

Single Post Permalink

View Thread: (STL) move_if algorithm, what's your take on it ?
  • User profile image
    Jonas_No

    There's no move_if algorithm so i wrote one.

    What's your opinion of it (improvements, bugs, etc...) ?

    template <typename FwdIt, typename Container, typename Predicate>
    inline FwdIt move_if(FwdIt first, FwdIt last, Container &cont, Predicate pred)
    {
        if (first == last)
            return last; // Empty so nothing to move
        const size_t size = count_if(first, last, pred);
        if (size == 0)
            return last; // Nothing to move
        cont.resize(size);
        FwdIt new_end = first;
        auto c = cont.begin();
        for (auto i = first; i != last; ++i)
        {
            if (pred(*i)) // Should it move it ?
                *c++ = move(*i);
            else
                *new_end++ = move(*i);
        }
        return new_end;
    }

    How you use it:

    int main()
    {
        vector<int> v(10);
        generate(v.begin(), v.end(), [] () -> int {
            static size_t i = 1;
            return i++ * 11;
        });
    
        vector<int> n;
        auto new_end = move_if(v.begin(), v.end(), n, [](int i){return (i % 2)==0;});
        v.erase(new_end, v.end());
    
        auto print_vec_int = [](vector<int> v) {
            cout << "[" << v.size() << "]";
            for_each(v.cbegin(), v.cend(), [](const int &i) {
                cout << " " << i;
            });
            cout << endl;
    
        };
    
        print_vec_int(v);
        print_vec_int(n);
    }
    /* Output:
    [5] 11 33 55 77 99
    [5] 22 44 66 88 110
    */