就算法而言,从连续数组中移除一组元素可以在两个部分中有效地完成.
这可以C++用擦除 - 移除习语来完成.
vector<T> v; // v = {0,1,2,3,0,0,7};
vector<T>::iterator it = remove(v.begin(),v.end(),e);
// move all elements not to be deleted to the front
// Yes, remove is not the brightest name for that.
// Especially as list::remove really remove elements from the list.
// now v = {1,2,3,7,?,?,?} results marked in question marks
// are implementation dependent.
v.erase(it,v.end());
// get rid of the elements marked as question marks.
// v = {1,2,3,7}
Run Code Online (Sandbox Code Playgroud)
现在,问号中元素的内容是未知的.我们唯一可以做的就是摆脱它们(通过覆盖它们,或者删除它们).
有remove没有擦除需要使用的现实世界情况?我能想到的唯一情况是
copy(src.begin(),src.end(),remove(v.begin(),v.end(),e),v.end());
Run Code Online (Sandbox Code Playgroud)
用As 替换所有s B,并要求所有新Bs都是连续的.没有太多意义.
编辑:是否有意义比contigious存储容器(其它任何东西deque和vector实际)?
如果确实我是正确的,为什么它实现为一个独立的算法,而不是vector::remove_if,dequeue::remove_if等等.
你的问题是错误的.相反,人们会问"我为什么要为每个容器重复实现这个相同的算法,而不是让它成为一个单独的自由函数"?
分离容器,迭代器和算法背后的关键思想是,在编写更多算法和更多容器时,不会出现复杂性爆炸.如果你想编写一个具有连续存储的新容器,你可以直接使用remove它(如果你提供转发或随机访问迭代器),而不需要复制任何代码.
某些容器实现自己的算法成员版本的唯一原因是因为它们可以比通用版本更好(例如std::set::findvs. std::find或者list::remove),或者因为它们可以做泛型版本不能做的事情(例如std::list::sortvs. std::sort) .但是如果可以的话,你应该使用免费版本来获得最大的通用性和通用性.
| 归档时间: |
|
| 查看次数: |
331 次 |
| 最近记录: |