我正在编写一个程序来帮助解决填字游戏。所以我从英语中所有单词的文本列表中获取一个单词,使每个单词成为字符向量,并将该向量与我拥有的任何起始字母的向量进行比较。它运行良好并为我提供了良好的输出,但每次我收到错误“libc++abi.dylib:以未捕获的 std::length_error: 类型异常终止”。
这是我的代码:
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <string>
#include <iterator>
using namespace std;
string getLetters() {
string word; // Get user letter, put in variable word
cout << "Enter a set of letters" << endl;
cin >> word;
return word;
}
int getLengthOfWord() {
int length; // Get length of word
cout << "Enter the number of letters in the word" << endl;
cin >> length;
return length;
}
// Change strings to vectors of chars
vector<char> stringToVector(string word) {
std::vector<char> v(word.begin(), word.end());
return v;
}
bool compareVectors(vector<char> userWord, vector<char> listWord, int length) {
if (listWord.size() != length) // Make sure the word from the list is the right length
{
return false;
}
int counter = 0; // Counter
for (int i = 0; i < userWord.size(); i++) { // Iterating through the two words
for (int j = 0; j < listWord.size(); j++) {
if (listWord[j] == userWord[i]) { // If the letters match
listWord.erase(listWord.begin() - 1 + j); // Erase the letter from the word
counter++; // Increase counter
break; // Break out of for loop
}
}
}
if (counter == userWord.size()) { // If there were as many matches as letters in user set
return true;
}
else {
return false;
}
}
int main() {
string example; // variable to put words
ifstream wordList; // New ifstream object
wordList.open("/Users/alexray/Dropbox/C++ Practice/WordJumbleSolver/wordsEn.txt"); //open word list
int length = getLengthOfWord(); // Get user input
string word = getLetters();
vector<char> vector1(stringToVector(word));
while (wordList.is_open()) {
getline(wordList, example); // Get word, put it in example variable
vector<char> vector2(stringToVector(example)); // Make word from list a vector
vector2.erase(vector2.end() - 1); // Erase escape character from end of word
if(compareVectors(vector1, vector2, length)) { // compare the vectors
cout << example << endl;
}
}
wordList.close(); // Close stream
return 0;
}
Run Code Online (Sandbox Code Playgroud)
通过谷歌搜索,我认为这是我的向量最初不够大以处理某些单词的问题,但是在为向量分配值之前执行 vector.reserve(some_number) 没有任何帮助。另外,我无法想象一个向量在 <20 个元素时会有任何问题。
谢谢您的帮助!(我是 C++ 的新手,所以如果我显然应该做一些不同的事情,请告诉我)。
编辑:我正在使用的文件是来自本网站的 wordsEn.txt 文件:http ://www-01.sil.org/linguistics/wordlists/english/
我看到的一个问题是您没有删除您声称要删除的字符:
listWord.erase(listWord.begin() - 1 + j);
Run Code Online (Sandbox Code Playgroud)
这不会删除jth序列中的字符。
这种失败的最简单的例子是 ifj == 0在循环开始时,第一个字符匹配。
只需简单地这样做:
listWord.erase(listWord.begin() + j);
Run Code Online (Sandbox Code Playgroud)