c++学習11


//今後6ヶ月で読む本の名前を格納するvectorコンテナを定義します.
//見た本の名前を記録するsetを定義します.
//このプログラムはvectorから読んだことのない本を選ぶことをサポートします.
//読書目的を記録するsetに、
//そして、既読目的setからその本の記録を削除することをサポートします.
//仮想6ヶ月後、既読と未読の書目を出力
#include <iostream>
#include <set>
#include <vector>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
vector<string> books;
set<string> readedBooks;
string name;
//       6         vector  
cout << "Enter names for books you'd like to read\(Ctrl+Z to end):"
<< endl;
while (cin >> name)
books.push_back(name);
cin.clear(); //         
bool timeOver = false;
string answer, bookName;
//                  
srand( (unsigned)time( NULL ) );
//                
while (!timeOver && !books.empty()) {
//     6          
cout << "Would you like to read a book?(Yes/No)" << endl;
cin >> answer;
if (answer[0] == 'y' answer[0] == 'Y') {
//  vector        
int i = rand() % books.size(); //         
bookName = books[i];
cout << "You can read this book: "
<< bookName << endl;
readedBooks.insert(bookName); //          
books.erase(books.begin() + i); //  vector       
cout << "Did you read it?(Yes/No)" << endl;
cin >> answer;
if (answer[0] == 'n' answer[0] == 'N') {
//       
readedBooks.erase(bookName); //           
books.push_back(bookName); //        vector 
}
}
cout << "Time over?(Yes/No)" << endl;
cin >> answer;
if (answer[0] == 'y' answer[0] == 'Y') {
//    6     
timeOver = true;
}
}
if (timeOver) {//    6     
//       
cout << "books read:" << endl;
for (set<string>::iterator sit = readedBooks.begin();
sit != readedBooks.end(); ++sit)
cout << *sit << endl;
//          
cout << "books not read:" << endl;
for (vector<string>::iterator vit = books.begin();
vit != books.end(); ++vit)
cout << *vit << endl;
}
else
cout << "Congratulations! You have read all these books."<<endl;
return 0;
}
//作者とその作品のmultimap容器を構築します.
//find関数を使用してmultimapで要素を検索し、eraseを呼び出して削除します.
//探している要素が存在しない場合でも、プログラムは正しく実行できます
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main()
{
multimap<string, string> authors;
string author, work, searchItem;
//          multimap  
do {
cout << "Enter author name(Ctrl+Z to end):" << endl;
cin >> author;
if (!cin)
break;
cout << "Enter author's works(Ctrl+Z to end):" << endl;
while (cin >> work)
authors.insert(make_pair(author, work));
cin.clear();//                      
}while (cin);
cin.clear(); //         
//        
cout << "Who is the author that you want erase:" << endl;
cin >> searchItem;
//              
multimap<string,string>::iterator iter =
authors.find(searchItem);
if (iter != authors.end())
//           
authors.erase(searchItem);
else
cout << "Can not find this author!" << endl;
//   multimap  
cout << "author\t\twork:" << endl;
for (iter = authors.begin(); iter != authors.end(); ++iter)
cout << iter->first << "\t\t" << iter->second << endl;
return 0;
}

find関数が返す反復器を判断し、その反復器がauthorsの有効な要素を指している場合にerase操作を行い、探している要素が存在しない場合でもプログラムが正しく実行されることを保証します.