Std :: remove_if does not remove all elements

At the input, I would like to delete all non-unique values. I want the subset after removing the double elements to be identical to the input. Somehow, some characters remain in the input, and not all characters are deleted. It appears that std :: map inside the predicate also reduces the size.

The predicate for std :: remove_if () that I use is:

template<class T>
class RemovePredicate {

    public:

        RemovePredicate() : m_oldsize(0) {}

        bool operator()(const T& value)
        {
            //
            bool retval;
            m_uniques[value] ='a'; // 'a' could be any value
            cout << m_uniques.size() << endl;
            retval = m_uniques.size() == m_oldsize;
            m_oldsize = m_uniques.size();
            return retval;
        }

    private:

        std::map<T, char>   m_uniques;
        unsigned            m_oldsize;

};

I designed the predicate in such a way that when I see an increase in size, I did not meet the input. Therefore, when the size does not match, I do not delete the input. When the size remains the same, I run into this input value again and then delete it.

Verification Code:

template<class T>
void print(T iterable)
{
    for (auto c : iterable)
        cout << c;
    cout << endl;
}


int main(int argc, char** argv){
    if (argc != 2)
        return 1;

    char * str= argv[1];

    vector <char> charvec (str, str + strlen(str));
    print(charvec);

    auto itend = std::remove_if(charvec.begin(),
                                charvec.end(),
                                RemovePredicate<char>()
                                );
    print(charvec);
    // apply erase remove idiom
    charvec.erase(itend, charvec.end()); 
    print(charvec);
    return 0;
}

input example:

./remove_duplicates deadbeef

Output

gives

deabef

But, as you can see, the output still has a double 'e'. But on the bright side, the original order is maintained.

?

+4
1

, .

map ( set unordered_set), . map , shared_ptr ( ).

+4

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


All Articles