Erasing vector::end from vector(从向量中擦除向量::end)
问题描述
当我使用时它是否正常工作(什么都不做)
Does it works correct(does nothing) when I use
vector<T> v;
v.erase(v.end());
我想使用类似的东西
v.erase(std::find(...));
我应该 if 是 v.end() 还是不是?
C++.com 和 CPPreference
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从向量中擦除向量::end
基础教程推荐
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- CString 到 char* 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
