代码如下
#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到达容器超尾迭代器之后跳出循环。