擦除和删除的区别

2022-01-07 00:00:00 c++ stl

我对 std::remove 算法的用法之间的差异感到有些困惑.具体来说,当我使用此算法时,我无法理解正在删除的内容.我写了一个像这样的小测试代码:

I am bit confused about the difference between the usage of std::remove algorithm. Specifically I am not able to understand what is being removed when I use this algorithm. I wrote a small test code like this:

std::vector<int> a;
a.push_back(1);
a.push_back(2);

std::remove(a.begin(), a.end(), 1);


int s = a.size();

std::vector<int>::iterator iter = a.begin();
std::vector<int>::iterator endIter = a.end();

std::cout<<"Using iter...
";
for(; iter != endIter; ++iter)
{
    std::cout<<*iter<<"
";
}

std::cout<<"Using size...
";
for(int i = 0; i < a.size(); ++i)
{
    std::cout<<a[i]<<"
";
}

两种情况下的输出都是 2,2.

The output was 2,2 in both the cases.

但是,如果我使用擦除和删除这样的东西:

However, if I use erase with the remove something like this:

a.erase(std::remove(a.begin(), a.end(), 1), a.end());

我得到的输出为 2.

所以我的问题是:

(1).除了将 std::remove 与擦除功能一起使用之外,还有其他用途吗.

(1). Is there any use of std::remove other than using it with erase function.

(2).即使在执行 std::remove 之后,为什么 a.size() 返回 2 而不是 1?

(2). Even after doing std::remove, why a.size() returns 2 and not 1?

我阅读了 Scott Meyer 的 Effective STL 书中关于擦除-删除习语的条目.但我仍然有这种困惑.

I read the item in Scott Meyer's Effective STL book about the erase-remove idiom. But am still having this confusion.

推荐答案

remove() 实际上并没有从容器中删除元素――它只会在已删除的元素之上向前分流未删除的元素元素.关键是要意识到remove() 不仅可以用于容器,还可以用于任意任意前向迭代器对:这意味着它不能 实际上删除元素,因为任意迭代器对不一定具有删除元素的能力.

remove() doesn't actually delete elements from the container -- it only shunts non-deleted elements forwards on top of deleted elements. The key is to realise that remove() is designed to work on not just a container but on any arbitrary forward iterator pair: that means it can't actually delete the elements, because an arbitrary iterator pair doesn't necessarily have the ability to delete elements.

例如,指向常规 C 数组开头和结尾的指针是前向迭代器,因此可以与 remove() 一起使用:

For example, pointers to the beginning and end of a regular C array are forward iterators and as such can be used with remove():

int foo[100];

...

remove(foo, foo + 100, 42);    // Remove all elements equal to 42

这里很明显remove()不能调整数组的大小!

Here it's obvious that remove() cannot resize the array!

相关文章