Debug Assertion Failed ! List iterator not dereferencable

代码如下

#include <list>
#include <iostream>
#include <ctime>
#include <algorithm>
#include <iomanip>
typedef std::list<int> lisInt;
void Print(lisInt L, lisInt P);
const int LIMIT{ 100 };
int main()
{
	/*Creat a random list*/
	lisInt List1;
	srand(time(0));
	int i = 0;
	while (i++ < LIMIT)
		List1.push_back(rand() % 100);
	List1.sort();
	std::cout << "\nList1 after soring:\n";
	for (auto x : List1)
		std::cout << std::setw(3) <<  x << ' ';
	std::cout << std::endl;

	/*Creat the latter list to choose*/
	lisInt List2;
	for (int i = 0; i < 5;)
		List2.push_back(i++);
	std::cout << "\nList2 after soring:\n";
	for (auto x : List2)
		std::cout << std::setw(3) << x << ' ';

	/*choose items from List1 according to List2*/
	std::cout << "\n\nChosen numbers in List1:\n";
	Print(List1,List2);

}

void Print(lisInt L, lisInt P)
{
	lisInt::iterator itr1 = L.begin();
	lisInt::iterator itr2 = P.begin();
	for (int i = 0; itr1 != L.end(); ++i,++itr1)
	{
		std::cout << '\t' << i << std::endl;
		if (i == *itr2)
		{
			std::cout << "The " << i << "th element is " << *itr1 << std::endl;
			if(++itr2 == P.end())
				break;
		}
	}
	std::cout << "Finished!\n";
}

报错如下:Debug Assertion Failed!  list iterator not dereferencable (迭代器不能参引)

关于debug assertion failed, 一般是指针问题。检查后发现是迭代器itr2在Print()函数里越界了。itr2到达List2.end()之后,对它进行了求值运算,因而出现错误。解决方法是在iter2到达容器超尾迭代器之后跳出循环。



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值