擦除和删除之间的区别 [英] Difference between erase and remove
问题描述
我对使用std :: remove算法之间的区别感到困惑。具体来说,我不能理解什么是当我使用这种算法被删除。我写了一个小测试代码,像这样:
std :: vector< int&一个;
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 {
std :: cout<< a [i]< \\ n;
}
在这两种情况下,输出为2,2。 b
$ b
但是,如果我使用erase删除这样的东西:
a.erase (std :: remove(a.begin(),a.end(),1),a.end());
我得到的结果为2。
所以我的问题是:
(1)。是否使用std :: remove除了使用它与擦除功能。
(2)。即使在做了std :: remove之后,为什么a.size()返回2而不是1?
我在Scott Meyer的有效STL书中阅读了有关erase-remove成语。
remove()
t实际上从容器中删除元素 - 它只是在删除的元素的顶部分流未删除的元素。关键是要认识到 remove()
被设计为不只是一个容器,而是任何任意的前向迭代器对:这意味着它不能实际删除元素,因为任意的迭代器对不一定具有删除元素的能力。
例如,指针正则C数组的开始和结束是前向迭代器,因此可以使用 remove()
:
int foo [100];
...
remove(foo,foo + 100,42); //删除所有等于42的元素
无法调整数组大小!
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...\n";
for(; iter != endIter; ++iter)
{
std::cout<<*iter<<"\n";
}
std::cout<<"Using size...\n";
for(int i = 0; i < a.size(); ++i)
{
std::cout<<a[i]<<"\n";
}
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());
I get the output as 2.
So my questions are:
(1). Is there any use of std::remove other than using it with erase function.
(2). Even after doing std::remove, why a.size() returns 2 and not 1?
I read the item in Scott Meyer's Effective STL book about the erase-remove idiom. But am still having this confusion.
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.
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
Here it's obvious that remove()
cannot resize the array!
这篇关于擦除和删除之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!