[英]C++ const_iterator not dereferencable?
I am getting a runtime error when trying to using const_iterators. 尝试使用const_iterators时出现运行时错误。 The error is: list iterator not dereferencable.
错误是:列表迭代器不可引用。 I understand that a const_iterator can't be dereferenced to assign a value into the list, but I am trying to dereference the iterator to access the value in the list.
我知道const_iterator不能被取消引用以将值分配给列表,但是我试图取消引用迭代器以访问列表中的值。 I'm using Visual Studio 2010 professional.
我正在使用Visual Studio 2010专业版。
I have researched this quite a bit but have not found anything that helps me to understand what I am doing wrong. 我对此进行了相当多的研究,但没有发现任何可以帮助我了解自己在做错事情的事情。
#include <list>
#include <iostream>
using namespace std;
template <typename T>
list<T> interleaveLists(const list<T>& l, const list<T>& m)
{
list<T> interleavedList;
list<T>::const_iterator iter1;
list<T>::const_iterator iter2;
list<T>::const_iterator iter3;
list<T>::const_iterator iter4;
iter1 = l.begin();
iter2 = l.end();
iter3 = m.begin();
iter4 = m.end();
while (iter1 != iter2 || iter3 !=iter4)
{
interleavedList.push_back(*iter1);
interleavedList.push_back(*iter3);
iter1++;
iter3++;
if (iter1 == iter2)
{
interleavedList.push_back(*iter3);
}
if (iter3 == iter4)
{
interleavedList.push_back(*iter1);
}
} // end while
return interleavedList;
} //end interleaveLists
//******************************************************************
int main()
{
list<int> list1;
list<int> list2;
list<int> list3;
list<int> newList;
// Create list1 = {40, -5, 66, -7, 8}
list1.push_back(40);
list1.push_back(-5);
list1.push_back(66);
list1.push_back(-7);
list1.push_back(8);
// Create list2 = {22, 3, -4}
list2.push_back(22);
list2.push_back(3);
list2.push_back(-4);
newList = interleaveLists(list1, list2);
while (!newList.empty())
{
cout << newList.front() << " ";
newList.pop_front();
}
cout << endl;
newList = interleaveLists(list3, list2);
while (!newList.empty())
{
cout << newList.front() << " ";
newList.pop_front();
}
cout << endl;
} // end main
You can loop out of range. 您可以超出范围。 If iter1==iter2, but iter3!=iter4, the following code would push_back(*iter1), although iter1 is already l.end().
如果iter1 == iter2,但是iter3!= iter4,则以下代码将为push_back(* iter1),尽管iter1已经是l.end()。
while (iter1 != iter2 || iter3 !=iter4)
{
interleavedList.push_back(*iter1);
interleavedList.push_back(*iter3);
The problem that you are trying to dereference an iterator that is equal to end(). 您试图取消引用等于end()的迭代器的问题。
while (iter1 != iter2 || iter3 !=iter4)
{
interleavedList.push_back(*iter1); // here is invalid code
interleavedList.push_back(*iter3); // here is invalid code
iter1++; // here is invalid code
iter3++; // here is invalid code
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.