I am trying to implement a class template for an Array
class that should provide a method to count elements equal to a given element, but I get wrong results. This is my code:
main.cpp
#include <iostream>
#include "array.h"
int main() {
int arr[] = {1, 2, 3, 2, 5, 2};
char brr[] = {'a', 'b', 'c', 'd', 'a'};
Array<int> A(arr, 6);
Array<int> B(0, 7);
Array<char> C(brr, 5);
std::cout << A.getCount(2) << std::endl;
std::cout << B.getCount(0) << std::endl;
std::cout << C.getCount('a') << std::endl;
return 0;
}
array.h
template <typename T> class Array {
private:
T* ptrStart;
int size;
public:
Array() {
this->ptrStart = nullptr;
this->size = 0;
}
Array(T defaultValue, int size) {
T arr[size];
for (int i = 0; i < size; i++) arr[i] = defaultValue;
this->size = size;
this->ptrStart = arr;
}
Array(T* arr, int size) {
this->size = size;
this->ptrStart = arr;
}
int getCount(T);
};
template <typename T> int Array<T>::getCount(T element) {
int count = 0;
for (int i = 0; i < this->size; i++) if (this->ptrStart[i] == element) count++;
return count;
}
expected output:
3
7
2
actual output:
3
0
2