STL“擦除 - 去除” idiom:为什么不“调整大小 - 删除”? [英] STL "erase-remove" idiom: Why not "resize-remove"?
问题描述
一般来说,从 std :: vector
中完全删除所需项目的好方法是 erase-remove idiom 。
It is commonly understood that a good way to fully delete desired items from a std::vector
is the erase-remove idiom.
如上述链接中所述(截至本发布日期)代码 erase-remove 成语如下:
As noted in the above link (as of the date of this posting), in code the erase-remove idiom looks like this:
int main()
{
// initialises a vector that holds the numbers from 0-9.
std::vector<int> v = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
// erase-remove idiom to completely eliminate the desired items from the vector
v.erase( std::remove( std::begin(v), std::end(v), 5 ), std::end(v) );
}
我想知道 resize-remove
idiom在功能和性能方面等同于 erase-remove
idiom。
I would like to know whether a resize-remove
idiom is equivalent in terms of functionality and performance to the erase-remove
idiom. Or, perhaps I am missing something obvious?
以下是 resize-remove
idiom等同于上述 erase-remove
idiom?
Is the following resize-remove
idiom equivalent to the above erase-remove
idiom?
int main()
{
std::vector<int> v = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
// Is this "resize-remove" approach equivalent to the "erase-remove" idiom?
v.resize( std::remove( std::begin(v), std::end(v), 5 ) - v.begin() );
}
推荐答案
两个原因:
-
std :: remove
,-
op需要随机访问迭代器。
std::remove
algorithm requires only Forward Iterator, but-
op requires Random Access Iterator.
std :: remove
表示容器的新端。逻辑上,我们应该清除[容器的新端,容器的旧端)。
The result of std::remove
means "the new end of container". Logically, we should erase [ "the new end of container" , "the old end of container" ).
这篇关于STL“擦除 - 去除” idiom:为什么不“调整大小 - 删除”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!