STLのmapのようなもの
STLのmapのようにキーとデータのペアを格納する簡単な低機能コンテナをvectorを使って作ってみた実験。iteratorとかはありません。
#include
#include
#include
using namespace std; template
class mymap { public: _Tdata& operator[](const _Tkey& key); void add(const _Tkey& key,const _Tdata& data); private: struct pair { _Tkey key; _Tdata data; }; vector
t; }; template
_Tdata& mymap<_Tkey,_Tdata>::operator[](const _Tkey& key) { pair tmp; vector
::iterator i = t.begin(); for(;i != t.end();i++){ if(i->key == key) return i->data; } //not found tmp.key = key; t.push_back(tmp); return (t.back()).data; } template
void mymap<_Tkey,_Tdata>::add(const _Tkey& key,const _Tdata& data) { pair tmp; tmp.key = key; tmp.data = data; t.push_back(tmp); } int main() { mymap
pu; mymap
pi; mymap
pe; pu.add('a',1); pu.add('z',26); pi.add(1,string("Hello!")); pi.add(2,string("Bye!")); pe.add(string("I am a "),string("student.")); pe.add(string("My name is "),string("Bush.")); cout << "-- use pu --" << endl; cout << pu['a'] << endl; cout << pu['z'] << endl; pu['k'] = 11; cout << pu['k'] << endl; cout << endl << "-- use pi -- " << endl; cout << pi[1] << endl; cout << pi[2] << endl; pi[3] = string("Bomber!!"); cout << pi[3] << endl; cout << endl << "-- use pe -- " << endl; string s1 = "I am a "; string s2 = "My name is "; cout << s1 << pe[s1] << endl; cout << s2 << pe[s2] << endl; string s3 = "I am live in "; pe[s3] = "Japan."; cout << s3 << pe[s3] << endl; return 0; }
実行例