擦除-删除习语:当删除返回超过末尾的迭代器时会发生什么?

发布于 2024-08-10 12:22:27 字数 951 浏览 9 评论 0 原文

当我阅读 Scott Meyers erase-remove idiom(第 32 项)时,我遇到了这个问题="nofollow noreferrer">“有效的STL”书。

vector<int> v; 
...
v.erase(remove(v.begin(), v.end(), 99), v.end());

remove基本上返回“新逻辑结束”以及从该范围的“新逻辑结束”开始的原始范围的元素并继续,直到范围的真正末尾是要从容器中删除的元素。

听起来不错。现在,让我问我的问题:

在上面的例子中,如果在向量 vremove 可以返回 v.end() >。它基本上是将past-the-end-iterator传递给erase方法。

  1. past-the-end-iterator 传递给 erase 方法时会发生什么?标准是否称其为 UB?
  2. 如果这是未定义的行为,那么 Scott Meyer 书中的erase-remove idiom示例应该如下所示:

  vector<int> v; 
    ...
    vector<int>::iterator newEndIter = remove(v.begin(), v.end(), 99);
    if(newEndIter != v.end() )
    {
     v.erase(newEndIter, v.end();
    }  

对此有什么想法吗?

I got this question when I was reading erase-remove idiom (item 32) from Scott Meyers "Effective STL” book.

vector<int> v; 
...
v.erase(remove(v.begin(), v.end(), 99), v.end());

remove basically returns the "new logical end” and elements of the original range that start at the "new logical end" of the range and continue until the real end of the range are the elements to be erased from container.

Sounds good. Now, let me ask my question:

In the above example, remove can return v.end() if 99 is not found in the vector v. It is basically passing past-the-end-iterator to erase method.

  1. What happens when past-the-end-iterator is passed to the erase method? Does standard says it a UB?
  2. If it is undefined behavior, then erase-remove idiom example in Scott Meyer’s book should have looked like:
  vector<int> v; 
    ...
    vector<int>::iterator newEndIter = remove(v.begin(), v.end(), 99);
    if(newEndIter != v.end() )
    {
     v.erase(newEndIter, v.end();
    }  

Any ideas on this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

陌上青苔 2024-08-17 12:22:27

我认为 v.erase(v.end(), v.end()) 会被很好地定义并且不会删除任何内容。

I would think v.erase(v.end(), v.end()) would be well defined and erase nothing.

放我走吧 2024-08-17 12:22:27

C++ 标准规定,erase(q1,q2) 成员“擦除 [q1,q2) 范围内的元素”(参见第 23.1.1 节)。由于范围不包括最后一个元素,

v.erase(v.end(), v.end());

因此有效并且不会删除任何内容。

The C++ standard says that the erase(q1,q2) member "erases the elements in the range [q1,q2)" (cf. section 23.1.1). Since the range excludes the last element,

v.erase(v.end(), v.end());

is valid and erases nothing.

嘿看小鸭子会跑 2024-08-17 12:22:27

C++ 参考声明:

如果 first==last,则迭代器 first 不需要取消引用:擦除空范围是无操作。

C++ Reference claims:

The iterator first does not need to be dereferenceable if first==last: erasing an empty range is a no-op.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文