listはシーケンスコンテナの一種で、一連の値を保存するリストのコンテナです。
listの書式は次のとおりです。
#include <list>
list<type>
次の例はstringのリスト(list)であるnamelistに保存した名前を検索する例です。
#include <iostream>
#include <string>
#include <list>
#include <algorithm>
#define BUFF_LEN 1024
using namespace std;
list<string> namelist;
// .endが入力されるまで、繰り返し名前を入力する
int GetNames()
{
int n = 0;
char buff[BUFF_LEN];
while(1)
{
cout << "名前は? >";
cin.getline(buff, BUFF_LEN);
if (string(buff).compare(".end") == 0)
break;
namelist.push_back(string(buff));
n++;
}
return n;
}
bool FindName()
{
char buff[BUFF_LEN];
cout << "探す名前は? >";
cin.getline(buff, BUFF_LEN);
list<string>::iterator s;
s = find(namelist.begin(), namelist.end(), string(buff));
if (s != namelist.end())
{
cout << *s << "は登録済みです。" << endl;
return true;
} else
cout << buff << "は登録されていません。" << endl;
return false;
}
int main(int argc, char *argv[])
{
GetNames();
FindName();
return 0;
}
実行結果は次のようになります。
名前は? >Kenta
名前は? >Tommy
名前は? >Summy
名前は? >.end
探す名前は? >Sunny
Sunnyは登録されていません。