fork download
  1. #include <iostream>
  2. #include <string>
  3.  
  4. template <typename TType, int TRows, int TCols>
  5. class TwoDArray {
  6. private:
  7. TType theArray[TRows][TCols];
  8. TType defSpace;
  9.  
  10. public:
  11. TwoDArray(TType def);
  12. ~TwoDArray();
  13. void insert(int r, int c, TType value);
  14. TType access(int r, int c);
  15. void remove(int r, int c);
  16. void print();
  17. int getNumRows() const { return TRows; }
  18. int getNumCols() const { return TCols; }
  19. };
  20.  
  21. //initializes the 2D Array
  22. template <typename TType, int TRows, int TCols>
  23. TwoDArray<TType, TRows, TCols>::TwoDArray(TType def) {
  24. defSpace = def;
  25. //sets all values to the default
  26. for(int i=0; i<TRows; i++) {
  27. for(int j=0; j<TCols; j++) {
  28. theArray[i][j] = defSpace;
  29. }
  30. }
  31. }
  32.  
  33. //deletes the 2D Array
  34. template<typename TType, int TRows, int TCols>
  35. TwoDArray<TType, TRows, TCols>::~TwoDArray() {}
  36.  
  37. //inserts value v at row r and column c
  38. template<typename TType, int TRows, int TCols>
  39. void TwoDArray<TType, TRows, TCols>::insert(int r, int c, TType value) {
  40. theArray[r][c] = value;
  41. }
  42.  
  43. //get value at row r, column c
  44. template<typename TType, int TRows, int TCols>
  45. TType TwoDArray<TType, TRows, TCols>::access(int r, int c) {
  46. TType result = theArray[r][c];
  47. return result;
  48. }
  49.  
  50. //set value at row r and column c back to default
  51. template<typename TType, int TRows, int TCols>
  52. void TwoDArray<TType, TRows, TCols>::remove(int r, int c) {
  53. theArray[r][c] = defSpace;
  54. }
  55.  
  56. //print the 2D Array
  57. template<typename TType, int TRows, int TCols>
  58. void TwoDArray<TType, TRows, TCols>::print() {
  59. for(int i=0; i<TRows; i++) {
  60. for(int j=0;j<TCols; j++) {
  61. std::cout << theArray[i][j];
  62. std::cout << " ";
  63. }
  64. std::cout << std::endl;
  65. }
  66. }
  67.  
  68. int main()
  69. {
  70. TwoDArray<int, 5, 5> i(0);
  71. i.insert(1, 1, 1);
  72. i.insert(1, 3, 1);
  73. i.insert(3, 2, 8);
  74. i.insert(2, 0, 3);
  75. i.insert(2, 4, 3);
  76. i.insert(3, 2, 8);
  77. i.print();
  78.  
  79. std::cout << "\n\n";
  80.  
  81. TwoDArray<std::string, 5, 5> s("o");
  82.  
  83. s.insert(0, 2, "North");
  84. s.insert(4, 2, "South");
  85. s.insert(2, 4, "East");
  86. s.insert(2, 0, "West");
  87. s.print();
  88.  
  89. return 0;
  90. }
  91.  
Success #stdin #stdout 0.01s 2860KB
stdin
Standard input is empty
stdout
0 0 0 0 0 
0 1 0 1 0 
3 0 0 0 3 
0 0 8 0 0 
0 0 0 0 0 


o o North o o 
o o o o o 
West o o o East 
o o o o o 
o o South o o