Vectors

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 #include <iostream>
#include <vector>
#include <algorithm>
using namespace 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;
Last edited on
You have a couple of problems.

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.

Topic archived. No new replies allowed.