Find index of an element within the array

Feb 15, 2019 at 4:04am
I have the following function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
template <typename T>
size_t FixedVector<T>::find(const T& value) {
// to be completed 
    size_t index_ = 0;

    for (size_t j = 0; j < size_; ++j) {
        if (array_[j] == value) {
            index_ = j;
        }
        else if ((array_[j] != value) || (size_ == 0)) {
            index_ = size_;
        }
    }
    return index_;

}



Here's my main.cpp

1
2
3
4
5
6
7
8
9
FixedVector<int> Array1(5);

Array1.push_back(1);
Array1.push_back(5);
Array1.push_back(10);

std::cout << "Value 5 is at index " << Array1.find(5) << std::endl;
std::cout << "Value 1 is at index " << Array1.find(1) << std::endl;


The output for both values are 3, which is the size of the array.
The function somehow always assigns size_ as index_ even though the value is indeed inside the array.

Is there any problem with my code?

Appreciate your help.
Feb 15, 2019 at 4:16am
You should probably try to break away from the for loop once you have found it, otherwise it will keep looping. Try that first. Either break, or just return j once the value has been found.
Feb 15, 2019 at 5:07am
Thank you so much. I did what you told me and it works now.
Topic archived. No new replies allowed.