2

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!";

2 Answers2

2

Try using count

int ans = count(randomIntegers.begin(), randomIntegers.end(),searchNumber) ;

See the code here in Ideone.

ABcDexter
  • 2,751
  • 4
  • 28
  • 40
  • 1
    I made a slight modification of your code [here](http://ideone.com/BBiBHF). I don't know why you use bits.h . Also you don't have to search for the element and then count it. Just count it. – Mads Dec 07 '16 at 09:58
  • @Mads, [bits/stdc++.h](http://stackoverflow.com/questions/25311011/how-does-include-bits-stdc-h-work-in-c) is a single header file for many other header files like vector, algorithm etc. And, for the sake of the preserving the original code by OP, i used search part :) – ABcDexter Dec 07 '16 at 10:00
  • 1
    @ABcDexter - that header is not standard C++. – Pete Becker Dec 07 '16 at 14:06
  • @PeteBecker Yes, you are right. The competitive programmers use it a lot :) – ABcDexter Dec 07 '16 at 14:36
0

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";
Roman Podymov
  • 4,168
  • 4
  • 30
  • 57