fork download
  1. #include <iostream>
  2. #include <fstream>
  3. #include <string>
  4.  
  5. using namespace std;
  6.  
  7. template <typename T>
  8. class TwoDArray {
  9. private:
  10. T** theArray;
  11. int numRows;
  12. int numCols;
  13. T defSpace;
  14.  
  15. public:
  16. TwoDArray<T> (int r, int c, T def);
  17. ~TwoDArray<T>();
  18. void insert(int r, int c, T value);
  19. T access(int r, int c);
  20. void remove(int r, int c);
  21. void print();
  22. int getNumRows();
  23. int getNumCols();
  24. };
  25.  
  26. //initializes the 2D Array
  27. template <typename T>
  28. TwoDArray<T>::TwoDArray(int r, int c, T def) {
  29. numRows = r;
  30. numCols = c;
  31. defSpace = def;
  32. theArray = new T*[r];
  33. for(int i=0; i<r; i++) {
  34. theArray[i] = new T[c];
  35. }
  36. //sets all values to the default
  37. for(int i=0; i<r; i++) {
  38. for(int j=0; j<c; j++) {
  39. theArray[i][j] = defSpace;
  40. }
  41. }
  42. }
  43.  
  44. //deletes the 2D Array
  45. template<typename T>
  46. TwoDArray<T>::~TwoDArray() {
  47. for(int i=0; i<numRows; i++) {
  48. delete[] theArray[i];
  49. }
  50. delete[] theArray;
  51. }
  52.  
  53. //inserts value v at row r and column c
  54. template<typename T>
  55. void TwoDArray<T>::insert(int r, int c, T value) {
  56. theArray[r][c] = value;
  57. }
  58.  
  59. //get value at row r, column c
  60. template<typename T>
  61. T TwoDArray<T>::access(int r, int c) {
  62. T result = theArray[r][c];
  63. return result;
  64. }
  65.  
  66. //set value at row r and column c back to default
  67. template<typename T>
  68. void TwoDArray<T>::remove(int r, int c) {
  69. theArray[r][c] = defSpace;
  70. }
  71.  
  72. //print the 2D Array
  73. template<typename T>
  74. void TwoDArray<T>::print() {
  75. for(int i=0; i<numRows; i++) {
  76. for(int j=0;j<numCols; j++) {
  77. std::cout << theArray[i][j];
  78. std::cout << " ";
  79. }
  80. std::cout << std::endl;
  81. }
  82. }
  83.  
  84. //gets number of rows for test
  85. template<typename T>
  86. int TwoDArray<T>::getNumRows() {
  87. return numRows;
  88. }
  89.  
  90. //gets number of columns for test
  91. template<typename T>
  92. int TwoDArray<T>::getNumCols() {
  93. return numCols;
  94. }
  95. int main()
  96. {
  97. TwoDArray<std::string>* s = new TwoDArray<std::string>(5, 5, "o");
  98.  
  99. s->insert(0, 2, "North");
  100. s->insert(4, 2, "South");
  101. s->insert(2, 4, "East");
  102. s->insert(2, 0, "West");
  103. s->print();
  104.  
  105. delete s;
  106.  
  107. return 0;
  108. }
  109.  
Success #stdin #stdout 0.01s 2816KB
stdin
Standard input is empty
stdout
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