我正在为我的类(class)写一本“字典”。我有一个称为NumOfWordsInFile[]
的int数组,其中NumOfWordsInFile[0]
对应于A.txt中有多少个单词,而NumOfWordsInFile[25]
对应于Z.txt
现在,我对26种不同的字母条件有了巨大的转变。我有一个名为AddWord(string word)
的函数。 AddWord获取传递给它的单词的第一个字母,并将其插入到适当的.txt文件中。现在这是问题所在。每次将一个单词添加到A.txt中时,我都必须将NumOfWordsInFile[0]
递增1。我想到的唯一方法就是使用这些巨大的开关。我也有一个deleteWord函数,如果删除了单词,它会反过来减少NumOfWordsInFile[]
。现在我不想有两个26例,但是问题是我不知道该怎么办。现在,我可以对delete函数做同样的事情,但是我真的不希望有数百行代码要经过。有一个更好的方法吗?AddWord
函数中的开关示例:
case 'w':
if (numOfWordsInFile[22] < maxWordsPerFile) {
fout.open(fileName.data(), ios::app);
fout << word << " " << endl;
numOfWordsInFile[22]++;
if (totalWordsInDict < maxWordsInDict) {
totalWordsInDict++;
}
return(Dictionary::success);
} else {
return(Dictionary::failure);
}
case 'x':
if (numOfWordsInFile[23] < maxWordsPerFile) {
fout.open(fileName.data(),ios::app);
fout << word << " " << endl;
numOfWordsInFile[23]++;
if (totalWordsInDict < maxWordsInDict) {
totalWordsInDict++;
}
return(Dictionary::success);
} else {
return(Dictionary::failure);
}
删除功能。
bool Dictionary::DeleteAWord(string word)
{
ofstream fout;
ifstream fin;
string x;
string fileName="#.txt";
int count=0;
vector <string> words;
bool deleted=false;
fileName[0]=toupper(word[0]);
fin.open(fileName.data()); //makes the file depending on the first letter of the argument "word"
while (fin >> x)
{
words.push_back(x);
count++;//number of elements in vector
}
if (SearchForWord(x))
{
for ( ;count > 0; count--)
{
if (words[count-1] == word)
{
// cout << "Found word " << word << " during search, now deleting" << endl;
words.erase(words.begin()+(count-1));
deleted = true;
/*
This clearly doesn't work and is what I need help with, I know why it
doesn't work but I don't know how to make it better than having another
huge switch.
*/
numOfWordsInFile[toupper(word[0])]--;
/*
*/
totalWordsInDict--;
fin.close();
}
}
if (deleted)
{
fout.open(fileName.data());
for (int i = 0; i < words.size(); i++)
fout << words[i] << endl;
return(Dictionary::success);
}
return(Dictionary::failure);
}
return(Dictionary::failure);
}
最佳答案
字符基本上是数字。 “a”为97,“b”为98,依此类推。
最简单的方法是简单地将每个numOfWordsInFile[n]
替换为numOfWordsInFile[current_char - 'a']
,针对每种情况重复的整个代码可能位于一个函数中,如下所示:
int AddWord(char current_char) {
if(numOfWordsInFile[current_char - 'a']<maxWordsPerFile){
fout.open(fileName.data(),ios::app);
fout<<word<<" "<<endl;
numOfWordsInFile[current_char - 'a']++;
if(totalWordsInDict<maxWordsInDict){
totalWordsInDict++;
}
return(Dictionary::success);
}else{
return(Dictionary::failure);
}
}
有关更通用的解决方案,请阅读有关哈希映射和函数指针的信息(例如,对于每个字符,您可能希望分配一个不同的函数。