STL Algorithm::Count()

本文介绍了如何使用C++ STL中的count()算法来计算向量中特定值出现的次数。通过示例代码详细展示了如何创建向量、填充随机数、应用count()函数并输出结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转载自:http://www.dreamincode.net/forums/topic/52509-stl-algorithmcount/

What do I need to know before studying this tutorial?
You should have a knowledge of vectors and vector iterators.

What does the count() algorithm do?
It counts the # of a specified value within a vector

The syntax for the count() algorithm:
int count = count(<where to begin searching>, <where to stop searching>, <value to search for>);

What to include:

#include <iostream> // just to output what's going on
#include <algorithm> // algorithms!
#include <vector> // vector to use algorithms on

using namespace std;

Next, we need to begin our int main () function. I'm gonna assume you know how to do this, and move on.

We need to declare a vector and a vector iterator:
vector <int> myVec; // create a vector called myVec
vector <int> :: iterator it; // create a vector iterator called it

We now need a loop to fill our vector with some values. Let's use some random numbers:
for (int i = 0; i < 9; ++i)
{
    int random = rand () % 5; // generate a random number
    myVec.push_back(random); // fill the vector with some values
}

Let's print the contents:
cout << "Contents: ";
for (it = myVec.begin(); it != myVec.end(); ++it)
    cout << *it << " "; // print the contents of myVec


Next is the count function. Ready? (Take a look at the syntax at the beginning of this tutorial to compare them)
int count_value = count (myVec.begin(), myVec.end(), 4);

Now all we need to do is print our count variable and exit the program:
cout << endl << "Number of 4s stored in vector: " << count_value;

cin.get (); // pause
return EXIT_SUCCESS; // everything went OK

For those of you who learn better by example, here is the complete code:
#include <iostream> // just to output what's going on
#include <algorithm> // algorithms!
#include <vector> // vector to use algorithms on

using namespace std;

int main ()
{
    vector <int> myVec; // create a vector called myVec
    vector <int> :: iterator it; // create a vector iterator called it

    for (int i = 0; i < 9; ++i)
    {
        int random = rand () % 5; // generate a random number
        myVec.push_back(random); // fill the vector with some values
    }

    cout << "Contents: ";
    for (it = myVec.begin(); it != myVec.end(); ++it)
        cout << *it << " "; // print the contents of myVec

    int count_value = count (myVec.begin(), myVec.end(), 4);

    cout << endl << "Number of 4s stored in vector: " << count_value;

    cin.get (); // pause
    return EXIT_SUCCESS; // everything went OK
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值