書籍の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
}
これはbooks
にname
Dの本を見つけ、または自動的にそれが存在しない場合はname
D帳を作成し、設定するためのbook
のメソッドを呼び出します発売日。あなたはbook
sがその場で作成したくない場合は
、あなたのオプションは使用することがある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
at
メソッドを取得するには、これにもC++ 11の標準サポートが必要です。
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を修正する(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))。不透明な文字列(または他の性質の識別子)を個別のオブジェクトにマッピングする独自のメカニズムを実装するのはあなた次第です。 –
検索で回答を見つける前に、要件を正しく記述する方法を検討する必要があります。私はこれを1対1のメンタリングのためのチャットルームに入れることをお勧めします。 Q&Aデータベースには適していません。 –