你可以按照名稱索引std::map
書籍。
std::map<std::string, book> books;
然後
bool modify(const std::string &name, int day, int month, int year)
{
books[name].setreleasedate(day, month, year);
return true; // always succeeds
}
這將找到name
d書books
,或自動,如果不存在,創建name
d書,然後調用book
的方法設置發佈日期。
如果你不想被動態創建book
就做,你的選擇是使用std::map::at
或std::map::find
std::map::at
版本:
bool modify(const std::string &name, int day, int month, int year)
{
try
{
books.at(name).setreleasedate(day, month, year);
return true;
}
catch(std::out_of_range &) // did not find named book
{
return false;
}
}
這具有在處理一個顯著的性能損失如果不知名的書籍經常被擡頭,那麼這個例外是不尋常的。正如名稱所暗示的那樣,例外只應用於例外事件。更多關於爲什麼可以在這裏閱讀,如果感興趣:Are Exceptions in C++ really slow
這也需要C++ 11標準支持來獲得at
方法。
std::map::find
版本:
bool modify(const std::string &name, int day, int month, int year)
{
std::map<std::string, book>::iterator found; // could be auto found if C++11 is enabled
found = books.find(name)
if (found != books.end()) // if search ended before the end of books
{
found->setreleasedate(day, month, year);
return true;
}
else // did not find named book
{
return false;
}
}
此版本需要更多的代碼,並增加了親近微不足道的成本所有的時間,但沒有失敗情況下的顯著處罰。
也被所有的C++支持回到標準化的開始。除非你使用Turbo C++進行開發,否則不應該有任何意外。
爲什麼你不能將一個對象作爲參數給一個函數? 'void modify(book book,int x,int y,int z)'工作得很好。如果你想傳遞一個引用而不是副本,或者'void modify(book&theBook,int x,int y,int z)'。 – immibis
簡短的答案在這裏:寫你自己的代碼來做到這一點。 C++ [沒有反射](https://en.wikipedia.org/wiki/Reflection_(computer_programming))。您需要實現自己的映射不透明字符串(或其他性質的標識符)的機制到離散對象中。 –
在通過搜索找到答案之前,您需要弄清楚如何正確描述您的需求!我建議把它帶入聊天室進行一對一的輔導;它不適合問答數據庫。 –