【问题标题】:Access violation when passing pointer to iterator and pointer to list传递指向迭代器的指针和指向列表的指针时访问冲突
【发布时间】:2015-03-27 15:59:03
【问题描述】:

我编写了一个程序来将两个排序列表合并为一个排序列表。这是在 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;
}

【问题讨论】:

  • 我推荐使用引用而不是指针,这样更简洁。

标签: list visual-c++ iterator


【解决方案1】:

我认为您是在递增指针而不是迭代器。先引用指针。:

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

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

}

【讨论】:

  • 我无法进入函数,所以我假设错误发生在函数调用中...我会再次检查。
猜你喜欢
  • 2014-03-16
  • 1970-01-01
  • 2018-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-29
  • 2011-08-04
  • 1970-01-01
相关资源
最近更新 更多