C ++ const_iterator不可解除引用?

时间:2013-10-29 18:11:28

标签: c++ const-iterator

尝试使用const_iterators时出现运行时错误。错误是:列出迭代器而不是dereferencable。我知道const_iterator不能被解引用来为列表赋值,但是我试图取消引用迭代器来访问列表中的值。我正在使用Visual Studio 2010专业版。

我已经对此进行了相当多的研究,但没有找到任何可以帮助我理解我做错的事情。

#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

2 个答案:

答案 0 :(得分:2)

您可以循环超出范围。如果iter1 == iter2,但是iter3!= iter4,则下面的代码将是push_back(* iter1),尽管iter1已经是l.end()。

while (iter1 != iter2 || iter3 !=iter4)
{
    interleavedList.push_back(*iter1);
    interleavedList.push_back(*iter3);

答案 1 :(得分:0)

您尝试取消引用等于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