字典类从文件中加载条目,然后对它们执行操作。然后,字典类将条目存储回文件中。
我想知道检查我的字典成员函数的参数是否是有效术语/定义的最佳方法。我曾想过两种可能的解决办法,但我愿意接受任何其他的解决办法。我可以检查传递给函数的参数,或者创建一个术语和定义类,然后让类检查。
我之所以要区分字符串和术语/定义,是因为我可以从文件中读取字符串,而不必遇到定义不以句点结束的情况或人为错误造成的其他情况。
#include "dictionary.h"
//*** @TODO: What constitutes a term/definition ***
bool dictionary::search_term(const std::string& term){
for(auto& it: entries){
if(it.first != term);
else return true;
}return false;
};
bool dictionary::erase_entry(const std::string& term){
if(search_term(term)){
entries.erase(term);
return true;
}else return false;
};
bool dictionary::define_term(const std::string& term, const std::string& definition){
if(search_term(term)){
entries[term] = definition;
return true;
}else return false;
};
bool dictionary::write_entry(const std::string& term, const std::string& definition){
if(!search_term(term)){
entries[term] = definition;
return true;
}else return false;
};
inline bool exists (const std::string& name) {
struct stat buffer;
return (stat (name.c_str(), &buffer) == 0);
}
bool dictionary::ofs_entries(const std::string& path){
std::string file = (path + title);
std::ofstream ofs(file.c_str());
if(!ofs) return false;
for(auto& it: entries){
ofs << it.first << ": " << it.second << '\n';
}ofs.close();
};
bool dictionary::ifs_entries(const std::string& path){
std::string file = (path + title);
if(!exists(file)) return false;
std::ifstream ifs(file.c_str());
if(!ifs) return false;
std::string entry;
while(true){
//read entries
if(!ifs.eof()) break;
}return true;
};#ifndef DICTIONARY_H
#define DICTIONARY_H
#include <algorithm>
#include <iterator>
#include <fstream>
#include <string>
#include <map>
class dictionary{
public:
dictionary(const std::string& title, const std::string& definition = "")
: entries{{title, definition}}, title(title){;};
bool write_entry(const std::string& term, const std::string& definition = "");
bool define_term(const std::string& term, const std::string& definition);
bool erase_entry(const std::string& term);
bool search_term(const std::string& term);
bool ofs_entries(const std::string& path);
bool ifs_entries(const std::string& path);
private:
std::map<std::string, std::string> entries;
std::string title;
};
#endif//DICTIONARY_H发布于 2015-07-31 03:19:30
工具
我注意到的第一件事是你在做一些你不需要做的工作。您正在使用一个std::map来保存您的键和值,但是您并没有使用内置的方法来查找条目。(在其他语言中,maps实际上被命名为dictionary!)整个search_term()方法可能如下所示:
bool dictionary::search_term(const std::string& term){
std::map<std::string, std::string>::iterator it = entries.find(term);
return it != entries.end();
};同样,erase_entry()方法可以只调用std::map::erase()方法。
在大多数情况下,您的变量和方法名称都非常好!不过,有一些我会改变的。exists()函数应该类似于file_exists(),因此它与检查字典中是否存在条目没有混淆。
另外,ofs_entries()和ifs_entries()是奇数名。我会叫他们像write_entries_to_file()和read_entries_from_file()。
https://codereview.stackexchange.com/questions/98636
复制相似问题