c++ STD::find_if使用结构谓词

C++ STD::find_if using structure predicate

本文关键字:结构 谓词 STD find c++ if      更新时间:2023-10-16
 key_struct kStruct;
 kStruct.x = 2;
 std::find_if(m_cueCommands.begin(), m_cueCommands.end(), find_MyInt(kStruct));
 struct key_struct
 {
   int x;
   string y;
   string z;
 }
 struct find_myInt : std::unary_function<key_struct, bool>
 {     
    int  x;     
    find_myInt(key_struct kStruct):myInt(kStruct.x){}     
    bool operator()(key_struct const& m) const
    {         
     return m.x == myInt;     
    }
 };

我很确定我有这一点搞砸了,但我认为它是适度接近。我要做的是,我有key_struct作为我地图中的键。我希望能够搜索密钥并返回我设置key_struct的信息。如果我将key_struct设置为x = 2,那么我只想返回int x等于2的地方。如果我设置x = 2和y = "testString",那么我只想返回x = 2和y = "testString"的值的子集。

我相信我的方法很接近,但是,我想我遗漏了一些东西。想法吗?

你总是想和x比较吗?还是只当x != 0?

Btw,在你的结构构造函数中似乎有一个错误:没有名为myInt的成员,因此它应该是:find_myInt(key_struct kStruct) : x(kStruct.x){}。但这并不重要,无论如何它都需要被改变。

这是我要尝试的。这是未经测试的,可能包含错误,布尔返回值的"计算"效率极低。无论如何…

要使用它,创建一个你想要匹配的结构体,正如你可以从代码中看到的,它只会尝试匹配x > 0, y != "" and z != ""。因此,如果将"search"结构体设置为x = 5, y = "" and z = "",它将匹配x == 5 (y &Z可以是任意的)

typedef std::pair<key_struct, your_value_type> yourMapType;
struct find_myStruct : std::unary_function<key_struct, bool>
{
  private:
    key_struct myStruct;
  public:
    find_myInt(key_struct const & kStruct): myStruct(kStruct) {}
    bool operator() (yourMapType const & m) const
    {
      bool result = true;
      if (myStruct.x > 0)
        result &= (myStruct.x == m.first.x);
      if (myStruct.y != "")
        result &= (myStruct.y == m.first.y);
      if (myStruct.z != "")
        result &= (myStruct.z == m.first.z);
      return result;
    }
};

[Edit]注意到您想要使用映射,所以我相应地更新了代码。仍然非常未经测试,请随意指出错误。

[Edit 2]如果您在实际创建映射时遇到问题,因为您在key_struct上没有严格的弱排序,那么应该这样做。

同样,未经测试的

可能包含错误。所有if的效率也很低,但是…请随意使用您最喜欢的卡诺地图求解器(我想到了BMin)。

struct cmp_key_struct
{
  bool operator() (key_struct const & lhs, key_struct const & rhs) const
  {
    bool result = (lhs.x < rhs.x);
    if ((!result) && (lhs.x == rhs.x))
    {
      result = (lhs.y < rhs.y);
      if ((!result) && (lhs.y == rhs.y))
        result = (lhs.z < rhs.z);
     }
     return result;
  }
};
std::map<key_struct, your_value_type, cmp_key_struct> yourMap;

更正后的版本:

 struct find_myInt : std::unary_function<key_struct, bool>
 {     
    int  myInt;     /// HERE
    find_myInt(key_struct kStruct):myInt(kStruct.x){}     
    bool operator()(key_struct const& m) const
    {         
     return m.x == myInt;     
    }
 };

您不需要在地图上使用find_if。如果您试图使用结构作为映射键,如您所说,您需要提供"严格弱排序"的比较。例如,使用"<"而不是"=="。然后将其与地图进行比较。或者重载struct中的<操作符。您可以使用[]运算符或mapfind()方法进行O(log n)搜索,其中find_if为O(n)。