本文介绍了STL删除不能按预期工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int main()
{

        const int SIZE = 10;
        int a[SIZE] = {10, 2, 35, 5, 10, 26, 67, 2, 5, 10};
        std::ostream_iterator< int > output(cout, " ");
        std::vector< int > v(a, a + SIZE);
        std::vector< int >::iterator newLastElement;

        cout << "contents of the vector: ";
        std::copy(v.begin(), v.end(), output);

        newLastElement = std::remove(v.begin(), v.end(), 10);
        cout << "\ncontents of the vector after remove: ";
        //std::copy(v.begin(), newLastElement, output);
                         //this gives the correct result : 2 35 5 26 67 2 5
        std::copy(v.begin(), v.end(), output);
          //this gives a 10 which was supposed to be removed : 2 35 5 26 67 2 5 2 5 10

        cout << endl;
        return 0;
}

数组中有三个10。

为什么在我们用remove函数删除所有10个数组后,数组v包含10。

why does the array v contains a 10 after we remove the all the 10s with remove function.

a href =http://ideone.com/rlxd8>此处

you can see the compiled output also here

推荐答案

实际上 std :: remove 不会从容器中删除该项目。引用自

Actually std::remove doesn't remove the item from the container. Quoted from here

也就是说, std :: remove 仅适用于一对迭代器,并且不知道实际包含项目的容器的任何内容。事实上, std :: remove 不可能知道底层容器,因为没有办法从一对迭代器去发现容器迭代器属于。因此 std :: remove 并不真正删除项目,只是因为它不能。从 移除容器中的项目的唯一方法是调用该容器上的成员函数。

That is, std::remove works with a pair of iterators only and does not know anything about the container which actually contains the items. In fact, it's not possible for std::remove to know the underlying container, because there is no way it can go from a pair of iterators to discover about the container to which the iterators belong. So std::remove doesn't really remove the items, simply because it cannot. The only way to actually remove an item from a container is to invoke a member function on that container.

项目,然后使用:

 v.erase(std::remove(v.begin(), v.end(), 10), v.end());






是如此常见和有用的是 std :: list 添加了另一个名为 list :: remove 的成员函数,它产生的效果与 erase-remove idiom。


The erase-remove idiom is so common and useful is that std::list has added another member function called list::remove which produces the same effect as that of the erase-remove idiom.

 std::list<int> l;
 //...
 l.remove(10); //it "actually" removes all elements with value 10!

这意味着你不需要使用 erase-remove idiom当你使用 std :: list 。您可以直接调用其成员函数 list :: remove

That means, you don't need to use erase-remove idiom when you work with std::list. You can directly call its member function list::remove.

这篇关于STL删除不能按预期工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 17:16
查看更多