Hellko

#7

May 12th, 2013
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.94 KB | None | 0 0
  1. /*/////////////////////////////////////////////////////////////////
  2. //Class asociated array.                                        ///
  3. //System requirments:                                           ///
  4. //for typename KEY, VALUE must be defined operators <<, ==.     ///
  5. //                                                              ///
  6. /////////////////////////////////////////////////////////////////*/
  7. #include <vector>
  8. #include <iomanip>
  9. #include <iostream>
  10. using namespace std;
  11.  
  12. template <class KEY, class VALUE>
  13. class mymap {
  14.     struct ITEM {KEY x; VALUE y;};
  15. private:
  16.     vector<ITEM> arr;
  17. public:
  18.     mymap() {}
  19.     int add(KEY, VALUE);
  20.     void list();
  21.     VALUE val(const KEY&) const;
  22.     VALUE operator[](const KEY&) const;
  23. };
  24.  
  25. template <class KEY, class VALUE>
  26. VALUE mymap<KEY,VALUE>::operator[](const KEY &key) const {
  27.     return this->val(key);
  28. }
  29.  
  30. template <class KEY, class VALUE>
  31. VALUE mymap<KEY,VALUE>::val(const KEY &key) const {
  32.     for(auto &p : arr) if(key==p.x) return p.y;
  33.     cerr<<"\nError: NOT VALUE FOR KEY \""<<key<<"\"! Default returned."<<endl;
  34.     return VALUE();
  35. }
  36.  
  37. template <class KEY, class VALUE>
  38. int mymap<KEY,VALUE>::add(KEY key, VALUE value) {
  39.     for(auto &p : arr) if(key==p.x) {cerr<<"\nError: KEY EXIST!\n"; return 0;}
  40.     ITEM tmp={key, value};
  41.     arr.push_back(tmp);
  42.     return 1;
  43. }
  44.  
  45. template <class KEY, class VALUE>
  46. void mymap<KEY,VALUE>::list() {
  47.     for(auto &p : arr)
  48.     cout<<setw(15)<<p.x<<": "<<setw(15)<<p.y<<endl;
  49. }
  50.  
  51. int main() {
  52.     mymap<string, double> A;
  53.     A.add("Fate",4.4);
  54.     A.add("Faith",5.5);
  55.     A.add("Delusion",8.8);
  56.     A.add("Delusion",0.0);
  57.     A.list();
  58.     string s1("Fate"),s2("fate"),s3("Faith"),s4("Delusion");
  59.     cout<<"Value for key \""<<s1<<"\": "<<A["Fate"]<<endl;
  60.     cout<<"Value for key \""<<s2<<"\": "<<A[s2]<<endl;
  61.     cout<<"Value for key \""<<s3<<"\": "<<A[s3]<<endl;
  62.     cout<<"Value for key \""<<s4<<"\": "<<A[s4]<<endl;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment