Hello guys. I've a problem with vectors and I can't realise what's wrong. My task:
Enter 2 numbers N and M. N shows what is your length of your vector and M shows which number you're looking in vector. I need to find how many times my number duplicates in vector and print it.
I have to use find & vectors.
#include <iostream>
#include <vector>
#include <algorithm>
usingnamespace std;
int main() {
vector<int> myVector;
vector<int>::iterator it;
int n, m, E, F(0);
cin >> n >> m;
for (unsigned i = 0; i < n; i++) {
cin >> E;
myVector.push_back(E);
}
for (unsigned i = 0; i < n; i++) {
it=find(myVector.begin(), myVector.end(), m);
if (it != myVector.end()) {
F++;
}
else F = 0;
}
cout << F << endl;
return 0;
1) Line 16: As you iterate through the vector at line 15, you're always starting the find at the beginning of the vector.. Therefore, you will always find the first m. Use begin()+i to start at the i'th element.
2) Line 20: You don't want to set F back to 0 here. Consider if the first iteration found a match, then on the next iteration you do not find a match. You still want F to reflect the count of duplicates.