c++ - 我的leetcode提交中出现运行时错误:地址释放后堆使用

标签 c++ breadth-first-search unordered-set

#include <bits/stdc++.h>
using namespace std;
#include <unordered_set>
#include <queue>
struct word {
    string s;
    int level;
    word(string a, int b)
        : s(a)
        , level(b)
    {
    }
};
bool isadj(string s1, string s2)
{
    int len = s1.length(), count = 0;
    for (int i = 0; i < len; i++) {
        if (s1[i] != s2[i])
            count++;
        if (count > 1)
            return false;
    }
    return count == 1 ? true : false;
}
int ladderLength(string beginWord, string endWord, vector<string>& wordList)
{
    unordered_set<string> st;
    for (string s : wordList)
        st.insert(s); // adding elements into a set
    if (st.find(endWord) == st.end())
        return 0;
    queue<word> q;
    q.push(word(beginWord, 0)); // initialising the queue

    while (!q.empty()) {
        word temp = q.front(); // pop the current string
        q.pop();
        if (temp.s == endWord)
            return temp.level;
        for (auto it = st.begin(); it != st.end(); it++) { // loop over the set to find strings at a distance of 1 and add them to the queue
            if (isadj(temp.s, *it)) // i have inserted code here to print the string *it
            {
                q.push(word(*it, temp.level + 1));
                st.erase(*it); // delete the element to avoid looping
            }
        }
    }
    return 0;
}

int main()
{
    // make dictionary
    vector<string> D;
    D.push_back("poon");
    D.push_back("plee");
    D.push_back("same");
    D.push_back("poie");
    D.push_back("plie");
    D.push_back("poin");
    D.push_back("plea");
    string start = "toon";
    string target = "plea";
    cout << "Length of shortest chain is: "
         << ladderLength(start, target, D);
    return 0;
}
我要解决的问题是https://leetcode.com/problems/word-ladder/
我无法跟踪正在使用程序中再次释放的内存的位置?
以下是我的调试尝试:
我试图在另一个在线IDE上运行它,该代码可以编译并成功运行,但是给出了错误的答案。为了对其进行调试,我在代码中插入了一些行,以打印所有与当前字符串相距1的字符串。令人惊讶的是,该集中似乎有一个空字符串。请帮助我了解我在哪里做错了。

最佳答案

unordered_set::erase 返回一个值,此返回值很重要。您不应该忽略它。
在您的情况下,一旦从集合中删除了某些内容,it无效。尝试增加它会导致未定义行为。
正确的方法是用返回的迭代器替换当前的迭代器,然后在循环期间不递增。

for (auto it = st.begin(); it != st.end(); )
    if (...) {
        // ...
        it = st.erase(*it);
    } else
        ++it;

关于c++ - 我的leetcode提交中出现运行时错误:地址释放后堆使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63602026/

相关文章:

c++ - 大多数顺序值指向同一对象的查找表?

c++ - 关闭调试,NDEBUG

c++ - 有没有一种方法可以在删除和插入c++中的元素时循环遍历multiset或unordered_set中的元素

c++ - tr1::hash 用于 boost::thread::id?

c++ - 为什么我得到一个 "' 初始化' : cannot convert from 'initializer list' to '_Objty' "error in C++?

c++ - Qt 中的 zlib - QtZlib 不存在

java - 如何将广度优先搜索转换为 Java 中的静态方法?

algorithm - 查找其中包含所需节点的强连接组件

java - 如何在一维数组Java中上下左右搜索

c++ - std::为无序集(或映射)插入迭代器?