C++:Storing/accessing 带指针的大对象以避免 运行 内存不足

C++: Storing/accessing large objects with pointers to avoid running out of memory

我有一个 C++ 应用程序需要同时将几个非常大的 unordered_maps 加载到内存中,结果我 运行 out of stack space 堆 space 在 运行 时间内(在一些大的 unordered_maps 已经加载之后):

granger(34190, 0x7fff73062300) malloc: *** mach_vm_map(size=8949833580846596096) failed (error code=3)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
libc++abi.dylib: terminating with uncaught exception of type std::bad_alloc: std::bad_alloc
[1]    34488 abort      ./granger

似乎一个潜在的解决方案是将这些大型数据结构中的一些 保留在堆中 存储为指针 ,允许我以避免 运行ning 内存不足。 这个逻辑正确吗?

如果是,这是我在尝试实施更改时遇到的下一个问题:

编辑: 第三个要点的示例代码:vector<string> medsForPatient = allMeds[aPatient.getDeid()]; returns 我在上面描述的错误。

这是否意味着当我尝试访问由指针定义的无序映射中的 key/value 对时,我不能使用正常的 [] 运算符?如果不是,可以使用什么解决方法?

编辑 2:好的,所以评论告诉我我 运行 堆 space,而不是堆栈 space,但这真的根本没有解决我的问题:我可以采取什么方法将所有数据结构同时放入内存而不 运行 退出可寻址内存 space?

编辑 3: 这是应用程序在 运行ning 时崩溃的函数:

unordered_map<string,string> makeMedSynonyms() {
    unordered_map<string,string> medSynonymsMap;
    string delimiters = "|";
    ifstream ifs(MED_SYNONYMS_FILE);
    string line;
    while(std::getline(ifs, line)) {
        vector<string> medSynVec;
        string::size_type lastPos = line.find_first_not_of(delimiters, 0);
        string::size_type pos = line.find_first_of(delimiters, lastPos);
        while(string::npos != pos || string::npos != lastPos) {
            medSynVec.push_back(line.substr(lastPos, pos - lastPos));
            lastPos = line.find_first_not_of(delimiters, pos);
            pos = line.find_first_of(delimiters, lastPos);
        }
        medSynonymsMap[medSynVec[0]] = medSynVec[1];
    }
    return medSynonymsMap;
}

函数的一个问题是:

  medSynonymsMap[medSynVec[0]] = medSynVec[1];

您没有检查 medSynVec 是否至少有 2 个条目。如果条目数 < 2,则上面的行调用未定义的行为。