0

So I have a Card class with _suit and _rank members:

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
}

I also have a vector vector<Card> Deck. What I would like to check is whether Deck has Cards that have the same _rank value. I have tried using std::adjecent_find but that only works for primitive data types(?). Of course a nested for loop could be used, but is there a more efficient alternative?

Kal
  • 1
  • 1
  • Are you aware of operator overloading [1](https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading) [2](https://en.cppreference.com/w/cpp/language/operators)? – 273K Feb 02 '22 at 03:53
  • "*I have tried using `std::adjecent_find` but that only works for primitive data types(?)*" - actually, it is overloaded to let you specify a custom predicate for comparing elements. – Remy Lebeau Feb 02 '22 at 03:55
  • Is it your intention to find only consecutive equivalent values, or are you trying to find _any_ that satisfy your criteria? `std::adjacent_find` is used to find two consecutive elements that compare equal (or whose `BinaryPredicate` returns `true`). – Human-Compiler Feb 02 '22 at 04:11

1 Answers1

1

Any of the algorithms of this nature can usually have a predicate which basically means a function that tells the algorithm what you are looking for. For example, std::find_if takes a UnaryPredicate:

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

which we could overload to suit your needs with a lambda, for eg:

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

You can apply something similar to adjacent_find but i will let you do this as an excersize.

Fantastic Mr Fox
  • 32,495
  • 27
  • 95
  • 175