我有这样的事情:
class Bar
{
public:
pair<string,string> one;
std::vector<string> cars;
Bar(string one, string two, string car);
};
class Car
{
public:
string rz;
Bar* owner;
Car(string car, Bar* p);
};
class Foo
{
public:
Foo ( void );
~Foo ( void );
int Count ( const string & one, const string & two) const;
int comparator (const Bar & first, const Bar & second) const;
std::vector<Bar> bars;
};
int Foo::comparator(const Bar & first, const Bar & second) const{
return first.name < …Run Code Online (Sandbox Code Playgroud) std::sort在类中定义时,我无法将该函数与我的自定义比较函数一起使用。
class Test {
private:
vector< vector<int> > mat;
bool compare(vector<int>, vector<int>);
public:
void sortMatrix();
}
bool Test::compare( vector<int> a, vector<int> b) {
return (a.back() < b.back());
}
void Test::sortMatrix() {
sort(vec.begin(), vec.end(), compare);
}
Run Code Online (Sandbox Code Playgroud)
我收到以下错误消息:
error: reference to non-static member function must be called
sort(vec.begin(), vec.end(), compare);
^~~~~~~
Run Code Online (Sandbox Code Playgroud)
然而compare(),当我sortMatrix()在没有任何类的文件 main.cpp 中定义和时,一切正常。我将不胜感激任何帮助和建议。
如何将指向成员函数的指针传递给std :: list.sort()?
这可能吗?谢谢
struct Node {
uint32_t ID;
char * Value;
};
class myClass {
private:
uint32_t myValueLength;
public:
list<queueNode *> MyQueue;
bool compare(Node * first, Node * second);
bool doStuff();
}
bool myClass::compare(Node * first, Node * second) {
unsigned int ii =0;
while (ii < myValueLength)
{
if (first-> Value[ii] < second-> Value[ii])
{
return true;
} else if (first-> Value[ii] > second-> Value[ii])
{
return false;
}
++ii;
}
return false;
}
bool myClass::doStuff()
{
list.sort(compare); …Run Code Online (Sandbox Code Playgroud) 可能重复:
使用成员函数作为比较器排序问题
是否可以在std :: sort中使用类方法作为比较器函数?
例如:
std::sort(list.begin(),list.end(),object->comparator) //Doesn't compile
Run Code Online (Sandbox Code Playgroud)
如果是的话,我是怎么做到的?
我需要为矢量排序定义一个比较器函数:
class Sched
{
public:
struct Op
{
// some data
};
typedef std::pair<Op*,Clk> OpSchedule;
void genSched() { std::sort(m_mappedOp.begin(),m_mappedOp.end(),cmp)}
private:
std::vector<OpSchedule> m_mappedOp;
bool cmp(const OpSchedule& l,const OpSchedule& r)
{
return l.second< r.second;
}
Run Code Online (Sandbox Code Playgroud)
我收到编译错误:
function call missing argument list; use '&Sched::cmp' to create a pointer to member.
Run Code Online (Sandbox Code Playgroud)
有人可以建议如何解决这个错误的原因是什么?谢谢
我试图在这里实现线性回归的代码,但由于返回几个错误而无法编译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 …Run Code Online (Sandbox Code Playgroud)