将指针传递给迭代器和指向列表的指针时发生访问冲突

时间:2015-01-28 16:36:55

标签: list visual-c++ iterator

我编写了一个程序,将两个已排序的列表合并到一个排序列表中。这是用c ++编写的。一旦第一个列表用尽,我有一个辅助函数来加载较长列表的所有剩余元素。我传入指向迭代器的指针以及指向较长列表的指针。调用函数fillToEnd时,我得到以下异常。为什么会这样?

  

MergeSortedLists.exe中0x00A37F0C处的未处理异常:0xC0000005:   访问冲突读取位置0xCCCCCCCC。

以下是代码:

// Win32Project1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include <list>

using namespace std;

void fillToEnd(list<int>::const_iterator * anIter, list<int> * aList, list<int> sortedList){

    for (*anIter; *anIter != (*aList).end(); anIter++)
    {
        sortedList.push_back(**anIter);
    }

}


int _tmain(int argc, _TCHAR* argv[])
{

    list<int> x = { 1, 4, 6, 8, 9, 11, 14, 25 };
    list<int> y = { 2, 3, 5, 7, 8, 9, 10, 12, 13, 24, 36, 47 };
    list<int> sortedList;
    bool hasFinished = false;
    list<int>::const_iterator ciX = x.begin();
    list<int>::const_iterator ciX_e = x.end();
    list<int>::const_iterator ciY = y.begin();
    list<int>::const_iterator ciY_e = y.end();
    while (!hasFinished)
    {
        if (*ciX < *ciY)
        {
            sortedList.push_back(*ciX++);
            if (ciX == ciX_e)
            {
                cout << &y;
                fillToEnd(&ciY, &y, sortedList);
                hasFinished = true;
            }
        }
        else
        {
            sortedList.push_back(*ciY++);
            if (ciY == ciY_e)
            {
                fillToEnd(&ciX, &x, sortedList);
                hasFinished = true;
            }
        }
    }

    for (int anInt : sortedList)
    {
        printf("%d,", anInt);
    }
    return 0;
}

1 个答案:

答案 0 :(得分:2)

我认为你正在递增指针而不是迭代器。首先遵循指针。:

void fillToEnd(list<int>::const_iterator * anIter, list<int> * aList, list<int> sortedList){

    for (*anIter; *anIter != (*aList).end(); ++(*anIter))
    {
        sortedList.push_back(**anIter);
    }

}