How to return number of occurences in a vector

I have a problem. I need to write a function that returns the number of times k occurs in v. How do I make it return the number of times k occurs in v? This is what I have so far.


int countOccurrences(const vector<int> & v, int k);

for (int i = 0; i < v.size(); ++i)
{
if (v[k] == v[i + 1])
}

Last edited on
You should use accumulator variable and then return it:
1
2
3
4
5
6
7
8
9
10
int countOccurrences(const vector<int> & v, int k)
{
    int count = 0;
    for (int i = 0; i < v.size(); ++i)
    {
        if (k == v[i])
            ++count;
    }
    return count;
}


I would use iterators but this is fine too, i think.
Topic archived. No new replies allowed.