自定义C++谓词并查找if

Custom C++ Predicate and find if

本文关键字:查找 if 谓词 C++ 自定义      更新时间:2023-10-16

所以我有一个赋值,它有这个数据结构

    struct ZipCode
{
    char s[4];
    int  zip;
    bool operator() (const ZipCode &lhs, const ZipCode &rhs) const
    {return lhs.s[1] < rhs.s[1];}
    bool operator() (const char* st, const int &z) const
    {return st == s && z == zip;}
    bool operator() (const int &z) const
    {return zip == z;}
};

然后,我将这些数组插入到STL:set中,并试图稍后找到一个具有特定zip的数组。我通过使用像这样的find_if来实现这一点

std::set<ZipCode, ZipCode>::iterator itz = find_if(mySet.begin(), mySet.end(),ZipCode()(0xbb77));

当我编译它时,我得到以下错误:

c: \program files(x86)\microsoft visual studio 10.0\vc\include\algithm(83):错误C2064:术语未计算为采用1个参数的函数

我不确定问题是什么,也不知道如何解决这个问题

您会得到错误,因为operator()是一个成员函数,所以您使用的函数有两个参数,this和0xbb77。

您可以改用set::find

如果要使用不同的类成员值进行搜索,则必须为ZipCode提供三个构造函数,其中每个构造函数都使用与运算符()重载之一相同的参数。然后添加一个运算符==(const-ZipCode&other)函数并去掉运算符()s。

我会把它打出来,但在iPad上很难做到。

首先,将一个结构同时作为信息的存储的函子使用三种不同的用途是糟糕的设计。这太复杂了。我差点以为std::set<ZipCode, ZipCode>是非法的。

其次,你的问题的干净解决方案应该是一张地图。std::map<int, std::array<char, 4>>。STL通用算法对std::set(通常是红黑树)中任何数据结构的良好特性一无所知,因此使用map::find