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
 
				
         
 
            
        基础教程推荐
- 常量变量在标题中不起作用 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
						 
						 
						 
						 
						 
				 
				 
				 
				