Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*/////////////////////////////////////////////////////////////////
- //Class asociated array. ///
- //System requirments: ///
- //for typename KEY, VALUE must be defined operators <<, ==. ///
- // ///
- /////////////////////////////////////////////////////////////////*/
- #include <vector>
- #include <iomanip>
- #include <iostream>
- using namespace std;
- template <class KEY, class VALUE>
- class mymap {
- struct ITEM {KEY x; VALUE y;};
- private:
- vector<ITEM> arr;
- public:
- mymap() {}
- int add(KEY, VALUE);
- void list();
- VALUE val(const KEY&) const;
- VALUE operator[](const KEY&) const;
- };
- template <class KEY, class VALUE>
- VALUE mymap<KEY,VALUE>::operator[](const KEY &key) const {
- return this->val(key);
- }
- template <class KEY, class VALUE>
- VALUE mymap<KEY,VALUE>::val(const KEY &key) const {
- for(auto &p : arr) if(key==p.x) return p.y;
- cerr<<"\nError: NOT VALUE FOR KEY \""<<key<<"\"! Default returned."<<endl;
- return VALUE();
- }
- template <class KEY, class VALUE>
- int mymap<KEY,VALUE>::add(KEY key, VALUE value) {
- for(auto &p : arr) if(key==p.x) {cerr<<"\nError: KEY EXIST!\n"; return 0;}
- ITEM tmp={key, value};
- arr.push_back(tmp);
- return 1;
- }
- template <class KEY, class VALUE>
- void mymap<KEY,VALUE>::list() {
- for(auto &p : arr)
- cout<<setw(15)<<p.x<<": "<<setw(15)<<p.y<<endl;
- }
- int main() {
- mymap<string, double> A;
- A.add("Fate",4.4);
- A.add("Faith",5.5);
- A.add("Delusion",8.8);
- A.add("Delusion",0.0);
- A.list();
- string s1("Fate"),s2("fate"),s3("Faith"),s4("Delusion");
- cout<<"Value for key \""<<s1<<"\": "<<A["Fate"]<<endl;
- cout<<"Value for key \""<<s2<<"\": "<<A[s2]<<endl;
- cout<<"Value for key \""<<s3<<"\": "<<A[s3]<<endl;
- cout<<"Value for key \""<<s4<<"\": "<<A[s4]<<endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment