从向量中擦除向量::end [英] Erasing vector::end from vector

查看:18
本文介绍了从向量中擦除向量::end的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用时它是否正常工作(什么都不做)

Does it works correct(does nothing) when I use

 vector<T> v;
 v.erase(v.end());

我想使用类似的东西

 v.erase(std::find(...));

我应该 ifv.end() 还是不是?
C++.comCPPreference

Should I if is it v.end() or not?
There is no info about it on C++.com and CPPreference

推荐答案

标准并没有完全说明,但是 v.erase(q) 是定义的,擦除指向的元素通过 [sequence.reqmts] 中的 q".这意味着 q 必须实际指向一个元素,而结束迭代器没有.传入 end 迭代器是未定义的行为.

The standard doesn't quite spell it out, but v.erase(q) is defined, "Erases the element pointed to by q" in [sequence.reqmts]. This means that q must actually point to an element, which the end iterator doesn't. Passing in the end iterator is undefined behavior.

不幸的是,你需要写:

auto it = std::find(...);
if (it != <the part of ... that specifies the end of the range searched>) {
    v.erase(it);
}

当然,你可以定义:

template typename<Sequence, Iterator>
Iterator my_erase(Sequence &s, Iterator it) {
    if (it == s.end()) return it;
    return s.erase(it);
}

my_erase(v, std::find(v.begin(), v.end(), whatever));

关联容器上的

c.erase() 返回 void,因此要将这个模板推广到所有容器,您需要一些 ->decltype 动作.

c.erase() on an associative container returns void, so to generalize this template to all containers you need some -> decltype action.

这篇关于从向量中擦除向量::end的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆