Hello, I'm currently practicing with vectors and I'm trying to properly display the element position when I search for a number in a vector of {1, 2, 3, 4, 5}.
If I input 5, the program will tell me it is found in element 4. What I'm having trouble with is having the program output multiple elements if there's multiple of the searched number. With a vector of {1, 2, 3, 4, 5, 5}, the output is still only showing element 4 when it should be listing both elements 4 and 5. I've posted the vector initialization and search function below.
#include <iostream>
#include <vector>
usingnamespace std;
void Search(vector<int> &myVector)
{
int x;
cout << "Enter the number you want to find. -> ";
cin >> x;
cout << endl;
bool found = false; // because we have not found the number yet
for(int y = 0; y < myVector.size(); y++)
{
if (x == myVector[y])
{
found = true; // if we've entered this if-clause, then 'found' is true
cout << "Entry was found in element: " << y << endl;
}
}
// if found remained false i.e. we never entered the if-clause
if(!found) cout << "Entry was not found." << endl;
}
int main()
{
vector<int> myVector{1, 2, 5, 4, 5, 5, 7, 5, 9};
Search(myVector);
}
Enter the number you want to find. -> 5
Entry was found in element: 2
Entry was found in element: 4
Entry was found in element: 5
Entry was found in element: 7
Process returned 0 (0x0) execution time : 0.703 s
Press any key to continue.
Enter the number you want to find. -> 8
Entry was not found.
Process returned 0 (0x0) execution time : 2.642 s
Press any key to continue.