为 std::sort 获取“非标准语法;使用 '&' 创建指向成员的指针”

ahm*_*bin -1 c++ vector

我试图在这里实现线性回归的代码,但由于返回几个错误而无法编译std::sort

#include "LinearRegression.h"
#include <iostream>
#include <algorithm>
#include <vector>

bool LinearRegression::custom_sort(double a, double b) /*sorts based on absolute min value or error*/
{
    double a1 = abs(a-0);
    double b1 = abs(b-0);
    return a1<b1;
}

void LinearRegression::predict()
{
    /*Intialization Phase*/
    double x[] = { 1, 2, 4, 3, 5 }; //defining x values
    double y[] = { 1, 3, 3, 2, 5 }; //defining y values
    double err;
    double b0 = 0; //initializing b0
    double b1 = 0; //initializing b1
    double alpha = 0.01; //intializing error rate
    std::vector<double>error; // array to store all error values

    /*Training Phase*/
    for (int i = 0; i < 20; i++) //
    {   
        int idx = i % 5; //for accessing index after every epoch
        double p = b0 + b1 * x[idx]; //calculate prediction
        err = p - y[idx]; //calculate error
        b0 = b0 - alpha * err; //update b0
        b1 = b1 - alpha * err * x[idx]; // updating b1
        std::cout << "B0=" << b0 << " " << "B1=" << b1 << " " << "error=" << err << std::endl; //print values after every update
        error.push_back(err);
    }
    std::sort(error.begin(),error.end(),custom_sort); //sorting based on error values
    std::cout << "Final Values are: " << "B0=" << b0 << " " << "B1=" << b1 << " " << "error=" << error[0] << std::endl;

    /*Testing Phase*/
    std::cout << "Enter a test x value";
    double test;
    std::cin >> test;
    double pred = b0 + b1 * test;
    std::cout << std::endl;
    std::cout << "The value predicted by the model= " << pred;
}
Run Code Online (Sandbox Code Playgroud)

我收到错误:

非标准语法;使用“&”创建指向成员的指针

未找到匹配的重载函数

对于这条线

std::sort(error.begin(),error.end(),custom_sort); 
Run Code Online (Sandbox Code Playgroud)

Evg*_*Evg 5

custom_sort是一个非静态成员函数,它不能sort直接使用,因为在幕后它需要三个参数,而不是两个 - 第一个是对象指针。

在您的特定示例中,custom_sort不使用任何数据成员,因此可以制作它staticstatic应该进入声明):

static bool LinearRegression::custom_sort(double a, double b);
Run Code Online (Sandbox Code Playgroud)

然后你可以写:

std::sort(error.begin(), error.end(), &custom_sort);
Run Code Online (Sandbox Code Playgroud)

请注意,您需要&形成一个指向成员函数的指针,如错误消息所示。但是,对于static成员函数,可以省略它(类似于自由函数)。

  • 一旦“custom_sort”函数被声明为“static”,您就不需要“&amp;LinearRegression::”——因为它是从该类中调用的。 (2认同)