如何使用count_if函数计算向量中元素的频率?

问题描述

我的代码

bool func(int i){
    if(i==x)return 1;
    else return 0;
}

int findFrequency(vector<int> v,int x){
    
    int ans=count_if(v.begin(),v.end(),func);
    return ans;
}

如何在count_if函数中传递“ x”? 这里,“ x”是向量中存在的要计数的数字。

解决方法

要计算向量中的特定值,可以使用std::count()

std::vector<int> v;
int x = 1;
auto c = std::count(v.begin(),v.end(),x);

如果要使用std::count_if(),则可以使用状态为以下的函数对象:

struct if_counter {
    int x;
    bool operator()(int y) { return x == y; }
};

auto x = 1;
auto c = std::count_if(v.begin(),if_counter{x});

基本上,这与使用lambda表达式所获得的效果相同:

int x = 1;
c = std::count_if(v.begin(),[x](int y){ return x == y; });

Complete Example

,

{ "name": "any name","category": 1,"price": 19000,"description": "Please Purchase","count": 5,"image": [ { "image" : i?? } ] } 函数内部使用lambda函数是一种很好的清洁方法。上面的答案@idclev指出了这一点,这是一个与您现有代码更相似的版本:

findFrequency