-
STL count()
Is there any alternative to count() function of STL, I don't have any problem with it, but just wanna know.
And how to do the same thing that count() does? Like check and count the number of times a given value appears in vector?
One more question can the count() function be used with arrays, or its limited to only STL containers ?
-
Any alternative? Make your own... look at the code in the <algorithm> header file to see how it works. It can be used with an array just as easily as an STL container.
-
Yes, you can use count on an array. I took the example code here:
http://www.cppreference.com/cppalgorithm/count.html
Bashed it about a bit to make a program using an array:
Code:
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int v[10];
for( int i = 0; i < 10; i++ ) {
v[i] = i;
}
int target_value = 3;
int num_items = count( &v[0], &v[10], target_value );
cout << "v contains " << num_items << " items matching " << target_value << endl;
};
--
Mats
-
If you're asking if they have 2 functions that do the same thing, then no (why would they?). There's also count_if(), but it works a little differently.
-
By the way, without looking at the implementation of count, I expect it does something similar to this:
Code:
template<typename IT, typename T>
int count(IT begin, IT end, T target)
{
int c = 0;
for(IT i = begin; i != end; i++)
if (*i == target) c++;
return c;
}
--
Mats
-