4

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;
     }
3
  • You could just use return std::find(array, array + size, obj) != (array + size); instead of writing a loop. Commented Sep 25, 2015 at 5:14
  • @PaulMcKenzie Its for an assignment and I am not allowed to use the standard library. Commented Sep 25, 2015 at 5:17
  • can't resist: you know nothing, jon snow Commented Sep 25, 2015 at 6:36

1 Answer 1

5

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;
 }
Sign up to request clarification or add additional context in comments.

3 Comments

Good solution. Some programmers (such as the Linux kernel devs) prefer to set toReturn and break, because then there's a single exit point they can set as a breakpoint.
@Lorehead in modern C++, you use RAII class destructors to do the common cleanup required at the exit point
They’re writing low-level C, it’s true.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.