c++ - std::map 插入陷入无限循环或给出访问冲突错误

标签 c++ access-violation stdmap

我在 .h 文件中声明了一个 std::map

#include "pl.h"
#include <conio.h>
#include <iostream>
#include <fstream>
#include <string>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <vector>
#include <map>

using namespace std;

class ReadingXDSLfile
{
public:

     ReadingXDSLfile();
     ~ReadingXDSLfile();
     void readDotXDSLFile(string fileName, ifstream &file);
     void writeNodesList();


protected:
    typedef std::map<std::string, int> nodesMap;

    nodesMap nodes;

    std::vector<string> nodesName;
    std::map<std::string, int>::iterator nodeItr, nodeItr1;
    string outFileName;
private:
};

在 .cpp 文件中,当我尝试使用以下代码行插入一个项目时,它给出了访问冲突错误

int counter=0;
string strNode;
...
....
....
std::pair<string, int>prNode (strNode, counter);
     nodes.insert(prNode);

错误:

Unhandled exception at 0x0043c5d9 in testMMHC.exe: 0xC0000005: Access violation reading location 0x0000002c.

现在我在函数(.cpp 文件)中声明了一个临时映射变量,它允许我插入。但是当我将临时映射复制到头文件中声明的全局映射时,它会进入无限循环并且永远不会退出。

它发生在头文件中声明的所有映射变量。

最佳答案

首先,在标题中为您的 map 声明一个 typedef 是可以的,但不要声明变量本身,除非您使用 extern。应该只有一个,并且应该在您的 .cpp 文件中。

在 .h 文件中:

#include <map>
#include <string>

typedef std::map<std::string, int> NodeMap;
extern NodeMap nodes;

接下来,您的 .cpp 文件:

NodeMap nodes;

最后,关于插入,您有多种可能的方法。

std::string strIndex = "foo";
int value = 0

// one way.
nodes[strIndex] = value;

// another way
nodes.insert(NodeMap::value_type(strIndex,value));

举几个例子。

编辑: OP 更改了问题的源内容,现在显示 nodes 不是全局变量,而是另一个类的成员变量。这个答案中关于 extern 的一切都变得毫无意义。

违规的偏移量表示正在通过空指针引用其中一个迭代器或类本身。 0x2C 距离 NULL 有 44 字节深,这向我表明 ReadingXDSLfile object 被引用可能来自 NULL 指针。

如果没有来自 OP 的更多关于如何分配和访问引用对象的信息,我恐怕只能提供一个关于如何在 header 中外部变量的定义明确的教程,它应该be evident 与这个问题无关。

关于c++ - std::map 插入陷入无限循环或给出访问冲突错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12876523/

相关文章:

c++ - 什么是并行 for 循环,应该如何/何时使用它?

c - Python Ctypes OSError : exception: access violation reading 0x00000000

c++ - std::map 的顺序

c - 为什么这段修改字符串的代码不起作用?

insert - 对于 std::map,如果必须调整容器大小且内存不可用,insert 将如何表现?

c++ - 在类声明中初始化 const 成员变量时 Debug模式下的异常

c++ - 将结构视为数据类型是否准确?

c++ - 在 n 处计算六次独立运行的斐波那契数的最大和最小时间

c++ - C++:如何在Windows 10上使用编译器MinGW 9.2.0安装OpenCV

c:使用动态数组访问冲突写入位置