Erasing items from an STL list

前端 未结 6 1920
北恋
北恋 2021-02-02 13:21

I want to make a function which moves items from one STL list to another if they match a certain condition.

This code is not the way to do it. The iterator will most lik

6条回答
  •  不要未来只要你来
    2021-02-02 13:53

    std::list::iterator endMatching =
        partition(myList.begin(), myList.end(), myCondition);
    myOtherList.splice(myOtherList.begin(), myList, endMatching, myList.end());
    

    Note that partition() gives you enough to discriminate matching objects from non matching ones. (list::splice() is cheap however)

    See the following code on a concrete case inspired from Now to remove elements that match a predicate?

    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    using namespace std;
    
    class CPred : public unary_function
    {
    public:
            CPred(const string& arString)
                    :mString(arString)
            {
            }
    
            bool operator()(const string& arString) const
            {
                    return (arString.find(mString) == std::string::npos);
            }
    private:
            string mString;
    };
    
    int main()
    {
            list Strings;
    
            Strings.push_back("213");
            Strings.push_back("145");
            Strings.push_back("ABC");
            Strings.push_back("167");
            Strings.push_back("DEF");
    
            cout << "Original list" << endl;
            copy(Strings.begin(), Strings.end(),ostream_iterator(cout,"\n"));
    
            CPred Pred("1");
    
            // Linear. Exactly last - first applications of pred, and at most (last - first)/2 swaps. 
            list::iterator end1 =
            partition(Strings.begin(), Strings.end(), Pred);
    
            list NotMatching;
    
            // This function is constant time. 
            NotMatching.splice(NotMatching.begin(),Strings, Strings.begin(), end1); 
    
            cout << "Elements matching with 1" << endl;
            copy(Strings.begin(), Strings.end(), ostream_iterator(cout,"\n"));
    
            cout << "Elements not matching with 1" << endl;
            copy(NotMatching.begin(), NotMatching.end(), ostream_iterator(cout,"\n"));
    
            return 0;
    }
    

提交回复
热议问题