【问题标题】:Finding an object with equal member values查找具有相同成员值的对象
【发布时间】:2022-02-02 03:40:45
【问题描述】:

所以我有一个Card 类,其中有_suit 和_rank 成员:

class Card {    
private:
    char _suit;
    int _rank;
public:
    Card(char, int);     //Constructor

    char suit() const;   //Returns the _suit value

    int rank() const;    //Returns the _rank value
}

我还有一个矢量vector<Card> Deck。我想检查的是Deck 是否有Cards 具有相同的_rank 值。我尝试过使用std::adjecent_find,但这仅适用于原始数据类型(?)。当然可以使用嵌套的 for 循环,但有没有更有效的替代方案?

【问题讨论】:

  • 你知道运算符重载12吗?
  • "我尝试过使用std::adjecent_find,但这仅适用于原始数据类型(?)" - 实际上,它被重载以允许您指定自定义谓词进行比较元素。
  • 您的意图是只找到连续的等效值,还是试图找到满足您条件的任何? std::adjacent_find 用于查找两个比较相等的连续元素(或BinaryPredicate 返回true)。

标签: c++ vector member


【解决方案1】:

任何这种性质的算法通常都可以有一个谓词,它基本上意味着一个函数,它告诉算法你在寻找什么。例如,std::find_if 采用 UnaryPredicate:

template< class InputIt, class UnaryPredicate >
InputIt find_if( InputIt first, InputIt last,
                 UnaryPredicate p );

我们可以使用 lambda 来重载以满足您的需求,例如:

auto predicate = [myCard](const Card& card) { 
    return myCard.rank() == card.rank();
}

你可以应用类似于adjacent_find 的东西,但我会让你做这个作为练习。

【讨论】:

  • 在这种情况下,std::adjacent_find() 具有接受 BinaryPredicate 以比较 2 个元素的重载。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-01
  • 1970-01-01
相关资源
最近更新 更多