C++ erase越界问题

#include <iostream>
	using std::cin;  using std::cout;
	using std::endl; using std::cerr;
#include <vector>
	using std::vector;

///
template<typename T1>
void show(T1 beg, T1 end)
{
	T1 tmp = end;
	--tmp;					// tmp pointer to last element
	while (beg != end)
	{
		if (beg != tmp)
		cout << *beg++ << " ";
		else
		cout << *beg++ << endl;
	}
}
///
int main(int argc, const char *argv[])
{
	int array[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
	vector<int> ivec(array, array+sizeof(array)/sizeof(int));
	show(ivec.begin(), ivec.end());
	std::vector<int>::iterator iter = ivec.end();
	--iter;										// 之所以不直接写成cout << *ivec.erase( (--ivec.end()) ) << endl; 是因为
												// (--ivec.end())在VC6.0下会报错, 这是VC6.0很老的缘故吧
	cout << *ivec.erase( iter ) << endl;		// 其实这句是非法的,当iter是指向容器内的最后一个元素,则返回的迭代器指向容器的超出末端的下一位置
	// 对这个位置的跌掉期解引用的后果是未定义的。 在VC6.0和linux下都返回9,这是因为删除最后一个元素并没有改变那块内存的数据内容,其实已经越界了。
	// 但是在VC2008中就会报错 可见没有运行时错误也不代表程序就没有错误
	show(ivec.begin(), ivec.end());

	return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值