【发布时间】:2011-04-03 23:13:07
【问题描述】:
我正在为我的班级编写“词典”。我有一个名为 NumOfWordsInFile[] 的 int 数组,其中 NumOfWordsInFile[0] 对应于 A.txt 中有多少个单词,NumOfWordsInFile[25] 对应于 Z.txt
现在我对 26 种不同的字母条件进行了巨大的切换。我有一个名为AddWord(string word) 的函数。 AddWord 获取传递给它的单词的第一个字母并将其插入到适当的 .txt 文件中。现在问题来了。每次在 A.txt 中添加一个单词时,我都必须将 NumOfWordsInFile[0] 增加 1。我能想到的唯一方法是使用这些巨大的开关。我还有一个 deleteWord 函数,如果这个词被删除,它会减少 NumOfWordsInFile[]。现在我不想有两个 26 箱开关,但问题是我不知道该怎么做。现在我可以对删除函数做同样的事情,但我真的不想有数百行代码要经过。有没有更好的方法来做到这一点?
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-z 的连续布局来完成你想要的。只要您只使用英文字符(正如 RedX 指出的那样),这是最好的解决方案。
标签: c++ performance switch-statement