Question

I am getting a runtime error when trying to using 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. I'm using Visual Studio 2010 professional.

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
Was it helpful?

Solution

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().

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

OTHER TIPS

The problem that you are trying to dereference an iterator that is equal to 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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top