fork download
  1. #include <iostream>
  2.  
  3. template<class T>
  4. class Array
  5. {
  6. public:
  7. Array();
  8. ~Array();
  9.  
  10. private:
  11.  
  12. };
  13.  
  14.  
  15. template<>
  16. class Array<bool>
  17. {
  18. public:
  19. explicit Array(size_t size);
  20. ~Array();
  21.  
  22. bool operator[](size_t i) const
  23. {
  24. return data[i / INTBITS] & (1 << (i%INTBITS));
  25. }
  26.  
  27. void Set(size_t i, bool v);
  28.  
  29. private:
  30. int *data;
  31. size_t size;
  32. size_t realSize;
  33.  
  34. static const int INTBITS = sizeof(int) * 8;
  35. };
  36.  
  37. Array<bool>::Array(size_t size) : size(size)
  38. {
  39. realSize = size / INTBITS + 1;
  40. data = new int[size / INTBITS + 1];
  41. for (size_t i = 0; i != realSize; ++i)
  42. {
  43. data[i] = 0;
  44. }
  45. }
  46.  
  47. Array<bool>::~Array()
  48. {
  49. delete[] data;
  50. data = nullptr;
  51. }
  52.  
  53. void Array<bool>::Set(size_t i, bool v)
  54. {
  55. if (v == true)
  56. {
  57. data[i / INTBITS] |= (1 << i%INTBITS);
  58. }
  59. else
  60. {
  61. int t = 0xffffffff ^ (1 << i%INTBITS);
  62. data[i / INTBITS] &= t;
  63. }
  64. }
  65.  
  66.  
  67. int main()
  68. {
  69. Array<bool> arr(10);
  70.  
  71. std::cout << "First loop:" << std::endl;
  72. for (size_t i = 0; i != 10; ++i)
  73. {
  74. arr.Set(i, true);
  75. std::cout << arr[i] << std::endl;
  76. }
  77.  
  78. std::cout << "Second loop:" << std::endl;
  79. arr.Set(0, false);
  80. for (size_t i = 0; i != 10; ++i)
  81. {
  82. if (i & 1)
  83. arr.Set(i, false);
  84. std::cout << arr[i] << std::endl;
  85. }
  86. return 0;
  87. }
Success #stdin #stdout 0s 3412KB
stdin
Standard input is empty
stdout
First loop:
1
1
1
1
1
1
1
1
1
1
Second loop:
0
0
1
0
1
0
1
0
1
0