简体   繁体   English

来自 While 循环 C++ 的分段错误

[英]Segmentation Fault from a While Loop C++

I'm trying to do a search from inside a map that would push all related children and later generations into a stack.我正在尝试从 map 内部进行搜索,这会将所有相关的子代和后代推入堆栈。 mined is a json object declared before. mined的是之前声明的 json object。

    if ( !mined[source].empty() ) {
        std::vector<std::string> minedDataVec = mined[source];
        while ( !minedDataVec.empty() ) {
            for (std::string s: minedDataVec) {
                stack.push(s);
                if ( !mined[s].empty() ) {
                    std::vector<std::string> minedDataVec = mined[s];
                } else {
                    minedDataVec.clear();
                }
            }
        }
    }

However, I'm getting a Segmentation Fault that I'm pretty sure has something to do with the while loop inside this code.但是,我遇到了一个分段错误,我很确定这与这段代码中的 while 循环有关。 Removing the while loop works but that would mean I'd have to manually add more code each time I want to search deeper within my map.删除 while 循环是可行的,但这意味着每次我想在 map 中进行更深入的搜索时,我都必须手动添加更多代码。

First, the vector named minedDataVec declared in the if block seems meaningless...首先,在if块中声明的名为minedDataVec的向量似乎毫无意义......

As for the Segmentation Fault, maybe it's because minedDataVec.clear() " Invalidates any references, pointers, or iterators referring to contained elements. " ( source ).至于分段错误,可能是因为minedDataVec.clear()使引用包含元素的任何引用、指针或迭代器无效。 ”(来源)。

The range-for loop for (std::string s: minedDataVec) has an implicit iterator to minedDataVec , which may become invalidated and cause a Segmentation Fault from an invalid read access. for (std::string s: minedDataVec)range-for循环对minedDataVec有一个隐式迭代器,它可能会变得无效并导致无效读取访问导致分段错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM