帮助我理解 std::erase
在《C++ In A Nutshell》一书中,有以下示例代码
std::vector<int> data
...
std::erase(std::remove(data.begin(), data.end(), 42),
data.end());
我认为“erase”是一个成员函数,所以不应该是“data.erase”而不是“std::erase”吗? C++ 编译器是否有某种方式可以告诉您要调用成员函数的成员,或者本书是否省略了擦除模板函数的任何文档,或者示例是否错误?
In the book 'C++ In A Nutshell', there is the following example code
std::vector<int> data
...
std::erase(std::remove(data.begin(), data.end(), 42),
data.end());
I thought that 'erase' was a member function, so shouldn't that be 'data.erase' rather than 'std::erase'?
Is there some way the c++ compiler can tell what member you wanted to call a member function on, or did the book omit any documentation of an erase template function, or is the example wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
erase
是一个成员函数。提供的样本不正确。erase
is a member function. The sample provided is incorrect.没有
std::erase
。std::map::erase
、std::list::erase
存在。但不存在std::erase
。查看这个问题幻影 std::erase。
There is no
std::erase
.std::map::erase
,std::list::erase
exists. But nostd::erase
exists.Look this question about phantom std::erase.
是的,erase 是一个成员函数,所以它应该是
data.erase()
而不是std::erase()
。Yes, erase is a member function, so it should be
data.erase()
instead ofstd::erase()
.你的观察是正确的。 “擦除”应该是一个成员函数。只有容器上的成员函数才能更改该容器的内存大小。
You observation is correct. 'Erase' should be a member function. Only a member function on a container can change the memory size of that container.
编辑:抱歉,他们不是通用擦除,只是仔细检查
Edit: Sorry their is no generic erase, just double checked
有一种称为 std::remove 的算法。并对数据结构调用擦除。 remove 将所有要删除的元素移动到迭代器范围的末尾,并返回要删除的第一个元素。如果找不到元素,则返回 end()。
因此,您可以在从 std::remove 的返回值和数据结构末尾开始的范围内调用擦除。
请参阅:http://www.sgi.com/tech/stl/remove.html< /a>
请注意,remove 不适用于有序数据结构,因为元素无法重新排列。
删除是线性的,因此将从末尾删除一个向量。因为它不需要在要删除的元素之后使元素冒泡。
与这样的 O(N**2) 相比
There is an algorithm called std::remove. And calling erase on the data structure. remove moves all the elements to be erased to the end of the iterator range and returns the first element to be removed. Returns end() if the element could not be found.
So then you call erase on range starting with the return value of std::remove and the end of the data structure.
See: http://www.sgi.com/tech/stl/remove.html
Note that remove won't work with ordered datastructures, as the elements can't be rearranged.
remove is linear, and so would be removing a vector from up to the end. As it wouldn't need to bubble up the elements after the elements to be removed.
compared to something like this which is O(N**2)