c++ - 如何在 C++ 中使用我的自定义比较创建一组

标签 c++ set c-strings

有人可以解释一下这个例子中发生了什么吗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/

相关文章:

ios - 创建一个 NSSet 数组,该数组具有另一个 NSArray 中存在的对象的不同属性值

java - 转换内部 advance for 循环以检查 null

image - 使用 image.Image 或 *image.RGBA 的 Set() 方法

c++ - 为什么在动态数组中自动解除对 char 指针的引用

c++ - 在二叉搜索树中检索对象

c++ - 确定 Qt 库链接

c++ - 如何清除gdb命令屏幕?

c++ - 是否可以在不创建项目的情况下在Visual Studio 2019中编译运行HelloWorld.cpp?

c - Printf 在 Ubuntu 中不工作

c++ - 在 constexpr 函数中返回一个 C 字符串 : why no warning from the compiler?