如何解决此程序中的运行时错误

时间:2017-05-03 05:47:52

标签: c++ dictionary

我运行这个程序,它给出了运行时错误

“运行时错误:退出代码为-1073741819”。

有人可以告诉我为什么会出现错误以及如何纠正错误吗?

程序正在找到梯形图(达到目标词的最短链的长度)。即给定一个字典,并且两个单词'start'和'target'(两者都是相同的长度)。如果存在,则查找从“开始”到“目标”的最小链的长度,使得链中的相邻单词仅相差一个字符,并且链中的每个单词是有效单词,即它存在于字典中。可以假设“目标”词存在于词典中,并且所有词典词的长度都相同。

#include<bits/stdc++.h>
using namespace std;

string dic[] = {"POON", "PLEE", "SAME", "POIE", "PLEA", "PLIE", "POIN"};

int n = sizeof(dic)/sizeof(dic[0]);

set<string> graph;

struct word
{
    string s;
    int d;
};

bool isAdj(string &s , string &t)
{
    int count = 0;

    for(int i=0; i<s.length() && i<t.length(); i++)
       if(s[i] != t[i])
          count++;

    return (count == 1);      
}

int shortestPath(string s , string d)
{
    queue<word> que;

    word source = {s , 0};

    que.push(source);

    word cur;
    //string t = "PLEA";
    while(!que.empty())
    {
        cur = que.front();
        if(cur.s == d)
           break;

        for(string t : graph)
        {
            if(isAdj(cur.s , t))
            {
                word temp = {t, cur.d + 1};

                que.push(temp);
                graph.erase(t);
            }
        }

        que.pop();

    }

    if(cur.s == d)
        return cur.d;
  return 0;
}

main()
{

    for(int i=0; i<n; i++)
        graph.insert(dic[i]);

    cout<<"  "<<shortestPath("TOON" , "PLEA")   ; 
}

问题链接在这里      http://www.geeksforgeeks.org/word-ladder-length-of-shortest-chain-to-reach-a-target-word/

提前谢谢。

1 个答案:

答案 0 :(得分:0)

评论有一个重点。

然而,它错过了另一个问题 - 您不必在该循环中编辑图形。

list<string> foundStrings;
for(string t : graph)
        {
            if(isAdj(cur.s , t))
            {
                foundStrings.push_back(t);
            }
         }
for(string t: foundStrings) {
   word temp = {t, cur.d + 1};
   que.push(temp);
   graph.erase(t);
}

(也可能有一些错误处理。)

基本上:如果你在迭代它时更改序列,你必须采取额外的预防措施,不能使用C ++ 11样式,但最好的选择是不要在那时修改它 - 第二个选项是使用迭代器并特别小心。