Reputation: 91
I have a working code for searching after a specific integer in a vector. But the problem that I have is that I want the output to show how have many times the integer was found as well. For example, if the values of the vector is {1,2,2,2,3,3,4,4} and you search for number 2, the output would be something liks this, '2 is in the vector, 3 times!'. Here is my code so far:
int searchNumber;
cout << "Enter a search number: ";
cin >> searchNumber;
bool found = find(randomIntegers.begin(), randomIntegers.end(),searchNumber) != randomIntegers.end();
if(found)
cout << searchNumber << " is in the vector!";
else
cout << searchNumber << " is NOT in the vector!";
Upvotes: 2
Views: 239
Reputation: 2941
Try using count
int ans = count(randomIntegers.begin(), randomIntegers.end(),searchNumber) ;
Upvotes: 2
Reputation: 4521
You can use the following code:
int searchNumber;
cout << "Enter a search number: ";
cin >> searchNumber;
vector<int> randomIntegers = {1,2,2,2,3,3,4,4};
long found = count(randomIntegers.begin(), randomIntegers.end(), searchNumber);
cout << searchNumber << " is in the vector " << found << " times";
Upvotes: 0