Hellko

Untitled

May 13th, 2013
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.08 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. for(unsigned int i=0; i<arr.size(); i++) if(key==arr[i].x) return arr[i].y;
  34. cerr<<"\nError: NOT VALUE FOR KEY \""<<key<<"\"! Default returned."<<endl;
  35. return VALUE();
  36. }
  37.  
  38. template <class KEY, class VALUE>
  39. int mymap<KEY,VALUE>::add(KEY key, VALUE value) {
  40. //for(auto &p : arr) if(key==p.x)
  41. for(unsigned int i=0; i<arr.size(); i++) if(key==arr[i].x) {cerr<<"\nError: KEY EXIST!\n"; return 0;}
  42. ITEM tmp={key, value};
  43. arr.push_back(tmp);
  44. return 1;
  45. }
  46.  
  47. template <class KEY, class VALUE>
  48. void mymap<KEY,VALUE>::list() {
  49. for(auto &p : arr)
  50. cout<<setw(15)<<p.x<<": "<<setw(15)<<p.y<<endl;
  51. }
  52.  
  53. int main() {
  54. mymap<string, double> A;
  55. A.add("Fate",4.4);
  56. A.add("Faith",5.5);
  57. A.add("Delusion",8.8);
  58. A.add("Delusion",0.0);
  59. A.list();
  60. string s1("Fate"),s2("fate"),s3("Faith"),s4("Delusion");
  61. cout<<"Value for key \""<<s1<<"\": "<<A["Fate"]<<endl;
  62. cout<<"Value for key \""<<s2<<"\": "<<A[s2]<<endl;
  63. cout<<"Value for key \""<<s3<<"\": "<<A[s3]<<endl;
  64. cout<<"Value for key \""<<s4<<"\": "<<A[s4]<<endl;
  65. }
Advertisement
Add Comment
Please, Sign In to add comment