Searching Vectors

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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

vector<int> myVector{1, 2, 3, 4, 5};

void Search(vector<int> &myVector)
{
	int x;
	cout << "Enter the number you want to find. -> ";
	cin >> x;
	cout << endl;

	for(int y = 0; y < myVector.size(); y++)
	{
		if (x == myVector[y])
		{
			cout << "Element ref. {0, 1, 2, 3, ...}" << endl;
			cout << "Entry was found in element(s):" << endl << y << endl << endl;
			return;
		}	
	}

	cout << "Entry was not found." << endl << endl;
	
}
You are returning as soon as you find the first match. Remove the return statement and you're good.
I've already tried completely removing "return", I end up with the same result as well as "Entry was not found".
I've modified the code a little, and it should work good now:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <vector>

using namespace 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.


That definitely fixed it, the help is very much appreciated!
Topic archived. No new replies allowed.