count_if算法中的C++编译器错误

kit*_*its 2 c++ countif

我正在运行一个简单的STL算法来计算小于50的元素数.该程序生成错误"被称为对象类型'int'不是函数或函数指针".我花了一整夜的时间来排除故障,并在stackoverflow上寻找类似的问题而没有成功,但是在这个时候我无处可去.如果有人能指出我的错误,我将不胜感激.

#include <iostream>
#include <numeric>
#include <functional>
#include <algorithm>
#include <vector>
#include <cstdlib>

using namespace std;

bool lessThan(double x)    //global function
{
    return (x < 50);
}

int main()
{
    vector<double> v1(5);    //create vector of 5 doubles
    for (auto i : v1) {    //for each element in v1...(auto used to determine type)
        v1[i] = rand() % 100;    //generate random numbers
        cout << v1[i] << endl;
        count_if(v1.begin(), v1.end(), lessThan(v1[i]));
    }

    return 0;
}  
Run Code Online (Sandbox Code Playgroud)

Som*_*ude 5

你有两个问题:第一个关于你的错误是因为你调用了函数,但是你应该只提供一个指向函数的指针.

第二个问题难以诊断,但是range-for语句为您提供容器的而不是索引.这意味着i它将是一个double值,您将获得其中五个值,并且每个值都是0.0.

为了解决最后一个问题,我建议你做一些这样的事情

for (auto& v : v1)
{
    v = some_value;
}

std::cout << "Number of items whose value is less than 50: "
          << std::count_if(std::begin(v1), std::end(v1), lessThan)
          << '\n';
Run Code Online (Sandbox Code Playgroud)