Reputation: 43
I have been trying to implement an array class in C++ and have been trying to implement a doesContain method that checks to see if a particular item is in the array or not. I was wondering if something like this would work or would even be a good way of doing it:
T *array;
int size;
public:
array(int length=50) {
size=length;
array= new T[length];
}
bool doesContain(const T &obj) {
bool bFlag = false;
for (int i = 0; i < size; ++i) {
if (obj == array[i]) {
bFlag = true;
}
}
return bFlag;
}
Upvotes: 4
Views: 713
Reputation: 98459
If you want to have a method that checks if an object is in the array, yes this will work. Provided the operator== is acceptable of course.
I recommend just doing a "return true" when you find a match, and a "return false" at the bottom.
bool doesContain(const T &obj) {
for (int i = 0; i < size; ++i) {
if (obj == array[i]) {
return true;
}
}
return false;
}
Upvotes: 5