fork download
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <map>
  4.  
  5. using namespace std;
  6.  
  7. class Array
  8. {
  9.  
  10. struct proxy
  11. {
  12. int operator =(int v)
  13. {
  14. m[s] = v;
  15. return v;
  16. }
  17.  
  18. operator int()
  19. {
  20. if (m.count(s)) return m[s];
  21. return 0;
  22. }
  23.  
  24. proxy(Array*a, size_t s):m(a->m),s(s){}
  25. map<size_t,int> &m;
  26. size_t s;
  27. };
  28. public:
  29. Array() = default;
  30.  
  31. proxy operator[](size_t s)
  32. {
  33. return proxy(this,s);
  34. }
  35.  
  36. size_t count() { return m.size(); }
  37.  
  38. private:
  39. map<size_t,int> m;
  40. };
  41.  
  42. int main(int argc, const char * argv[])
  43. {
  44. Array a;
  45. a[5] = 4;
  46. for(int i = 0; i < 7; ++i) cout << a[i] << " ";
  47. cout << "\n" << a.count() << endl;
  48. }
  49.  
Success #stdin #stdout 0s 4532KB
stdin
Standard input is empty
stdout
0 0 0 0 0 4 0 
1