map / set iterator no dereferencable似乎没有理由

时间:2017-03-15 20:27:58

标签: c++ iterator maps dereference

我编写了这个程序来检查列表中给出的单词是否是彼此的字谜,并且由于某种原因,我的程序似乎只能运行一半,直到我得到一个运行时错误,表示" map / set迭代器不可解除错误"。我一直盯着这一段时间并试图调试它而我无法弄清楚问题,所以我希望有人在这里?以下是代码:

// Anagrams.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <map>
#include <algorithm>
#include <set>


using namespace std;

int main()
{
    ifstream ifs("words.txt");// opens file
    if (!ifs) {
        cout << "no file";
        exit(1);
    }

    set<string>anagrams;
    map<string, string>words;
    string word;
    while (ifs >> word) {
        string sortedWord = word;
        sort(sortedWord.begin(), sortedWord.end());
        words.insert(pair<string, string>(word, sortedWord));
    }

    for (map<string, string>::iterator i = words.begin(); i != words.end(); i++) {
        //cout << "test i for loop" << endl;
        for (map<string, string>::iterator j = words.begin(); j != words.end(); j++) {
            //cout << "test j for loop" << endl;
            if (i->first == j->first) {
                j++;
            }
            if (i->second == j->second) {
                anagrams.insert(i->first);
                anagrams.insert(j->first);
                for (set<string>::iterator i = anagrams.begin(); i != anagrams.end(); i++) {
                    cout << *i << " ";
                }
                cout << endl;
                anagrams.clear();
                //cout << i->first << " is an anagram of " << j->first << " and their sorted version is " << i->second << endl;

            }
        }
    }
    return 0;
}

以下是单词列表:

monday
dynamo
abbot
acne
alert
alter
baby
Baby
BABY
best
bets
cane
later
Unix
UNIX

,在得到运行时弹出错误之前输出是这个:

acne cane
alert alter
alert later
alert alter
alert later
best bets
best bets
acne cane
dynamo monday
alert later
alert later
dynamo monday

然后是错误。

(请原谅我糟糕的输出,我可以稍后解决。现在更关注错误)

由于

0 个答案:

没有答案