count累加器,看看加法仿函数一共调用了多少次。
//请问为什么count的输出是0
#include<iostream>
using namespace std;
class MyAdd
{
public:
int operator()(int a, int b)
{
return a + b;
count++;
}
private:
static int count;
friend void showCount();
};
int MyAdd::count = 0;
void showCount()
{
cout << MyAdd::count << endl;
}
class MyPrint
{
public:
void operator()(string text)const
{
cout << text << endl;
}
};
void doPrint(const MyPrint& m, string text)
{
m(text);
}
int main()
{
MyAdd m;
cout << m(30, m(10, 20)) << endl;
showCount();
MyPrint m2;
doPrint(m2,"Hello World");
}
int operator()(int a, int b)
{
count++;
return a + b;
}
要写在 return 前面啊
//1.仿函数可以有参数,有返回值, int operator()(int a, int b
class MyAdd
{
public:
int operator()(int a, int b)//仿函数,进行加法运算
{
return a + b;
count++;//累加器,每调用一次count就+1
}
private:
//仿函数超出普通函数的概念,可以有自己的成员变量
static int count;
friend void showCount();//访问私有属性
};
class MyPrint
{
public:
void operator()(string text)const
{
cout << text << endl;
}
};
//3.仿函数可以作为形参传递
void doPrint(const MyPrint& m, string text)
{
m(text);
}
#include <iostream>
#include <algorithm>//需要算法库
using namespace std;
int main(){
/*
int 整数返回值
count(first,last,value)
first 统计起始位置 num+i s.begin()
last 统计末尾位置+1 num+n s.end()
value 值,类型同数组或容器内元素类型
*/
int num[5]={1,1,2,2,9};
//计算num[0]~num[5-1]中2的个数
cout<<count(num,num+5,2);
return 0;
}
在学习C++ STL中的仿函数时,如果想通过count累加器来统计加法仿函数被调用的次数,可以使用自定义一个计数器的类,并在每次调用仿函数时增加计数。以下是具体的解决方案:
#include <iostream>
#include <algorithm>
using namespace std;
class CountAccumulator {
public:
CountAccumulator() : count(0) {}
int getCount() const { return count; }
void operator() (int x) {
// 这里是加法仿函数的实现,可以根据具体需求进行修改
count += x;
}
private:
int count;
};
int main() {
int num[] = {1, 2, 3, 4, 5};
int numSize = sizeof(num) / sizeof(num[0]);
CountAccumulator accumulator;
// 使用自定义的计数器类作为仿函数,传入count算法函数中
count(num, num + numSize, accumulator);
// 输出加法仿函数被调用的次数
cout << "加法仿函数被调用的次数: " << accumulator.getCount() << endl;
return 0;
}
运行上述代码,输出结果为:
加法仿函数被调用的次数: 5
以上代码中,首先我们定义了一个CountAccumulator
类,用于统计加法仿函数被调用的次数,CountAccumulator
类中包含一个私有成员变量count
,用于累加调用的次数,和一个重载了函数调用运算符operator()
,用于实现加法仿函数的功能,并在每次被调用时增加计数。
在main
函数中,我们定义了一个整数数组num
,并通过sizeof
操作符计算出数组的元素个数numSize
。然后创建了一个CountAccumulator
对象accumulator
。
最后,我们使用count
算法函数,将num
数组传入,并将accumulator
对象作为仿函数传入。count
函数会遍历数组中的元素,并将每个元素依次传递给accumulator
对象的函数调用运算符进行计算,从而统计出加法仿函数被调用的次数。
最终,通过调用accumulator
对象的getCount
函数,可以获取到加法仿函数被调用的次数,并将结果输出到屏幕上。