有人可以解释一下这个例子中发生了什么吗here ?
他们声明以下内容:
bool fncomp (int lhs, int rhs) {return lhs<rhs;}
然后使用为:
bool(*fn_pt)(int,int) = fncomp;
std::set<int,bool(*)(int,int)> sixth (fn_pt)
而算法库中的排序方法示例here
可以这样做:
bool myfunction (int i,int j) { return (i<j); }
std::sort (myvector.begin()+4, myvector.end(), myfunction);
我也不明白以下内容:
struct classcomp {
bool operator() (const int& lhs, const int& rhs) const
{return lhs<rhs;}
};
这个关键字运算符(不像op.重载中那样后面跟着运算符)...它的含义是什么?那里应用的任何运算符都会有这种行为吗?而这个const修饰符……它造成的效果是什么?
我试图制作一组 C 风格字符串,如下所示:
typedef struct
{
char grid[7];
} wrap;
bool compare(wrap w1, wrap w2)
{
return strcmp(w1.grid, w2.grid) == -1;
}
set <wrap, compare> myset;
我认为我可以创建一个集合来定义我的排序函数,就像我从算法库中调用排序一样......一旦它没有编译,我就去了文档并看到了这个让我困惑的语法......我是否需要像我粘贴到此处的第一个示例一样声明一个指向函数的指针?
最佳答案
struct classcomp {
bool operator() (const int& lhs, const int& rhs) const
{return lhs<rhs;}
};
通过重载函数调用运算符来定义仿函数。要使用函数,您可以执行以下操作:
int main() {
std::set <wrap, bool (*)(wrap,wrap)> myset(compare);
return 0;
}
另一种选择是将运算符定义为 wrap
类的一部分:
struct wrap {
char grid[7];
bool operator<(const wrap& rhs) const {
return strcmp(this->grid, rhs.grid) == -1;
}
};
int main() {
wrap a;
std::set <wrap> myset;
myset.insert(a);
return 0;
}
关于c++ - 如何在 C++ 中使用我的自定义比较创建一组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24359014/