检查 std::array 中的对象是否具有相同的成员数据
To check objects inside std::array has identical member data
Cards.h
class Card
{
public:
// Card suits
struct Suit
{
// Suits in order
enum Enum
{
Clubs,
Diamonds,
Hearts,
Spades,
};
};
// Card rank
struct Rank
{
// Ranks with aces low
enum Enum
{
Ace,
Two,
King,
....
...
};
};
// constructors
//get & set functions
//predicate
friend bool compareCardsSuit(const Card & cardlhs, const Card & cardrhs)
{
return cardlhs.GetSuit() == cardrhs.GetSuit();
}
friend bool operator==(Card const& lhs, Card const& rhs) // THis func is used for some other purpose
{
// We only care about rank during equality
return lhs.m_rank == rhs.m_rank;
}
手.h
class Hand
{
public:
static int const Size = 5;
// The type of hand we have
struct Type
{
// Type of hand in accending order
enum Enum
{
HighCard,// Five cards which do not form any of the combinations below
Flush, // Five cards of the same suit
bla,
bla..
};
};
// Object creation
// other functiosn
private:
mutable std::array<Card, Size> m_cards;
Type::Enum m_type;
// Hand calculations
Type::Enum Evaluate();
手.cpp
Hand::Type::Enum Hand::Evaluate()
{
std::equal(m_cards.begin(), m_cards.end(), compareCardsSuit); // got error
{
return Hand::Type::Flush;
}
// Return our hand
return Hand::Type::HighCard;
}
我想要的只是检查m_cards的成员数据是否具有相同的花色,然后返回同花顺。
我在下面收到错误
错误3 错误 C2678:二进制"==":找不到采用类型为"Card"的左侧操作数的运算符(或者没有可接受的转换)
错误2 错误 C2171:"++":在类型为"布尔 (__cdecl *)(常量卡 &,常量卡 &)"的操作数上非法
要检查特定的西装,您可以使用std::all_of
const bool areAllClubs = std::all_of(m_cards.cbegin(), m_cards.cend(),
[](const Card& card) {
return card.GetSuit() == Card::Suit::Clubs;
}));
要检查所有相邻的卡是否正在验证您可以使用的一些标准std::adjacent_find
const auto it = std::adjacent_find(m_cards.cbegin(), m_cards.cend(),
[](const Card& left, const Card& right) {
return left.GetSuit() != right.GetSuit();
});
if (it == m_cards.end()) {
// All cards have same suit
}
else {
const auto& card = *it; // Points to a first card mismatched
}
或者干脆
const auto it = std::adjacent_find(m_cards.begin(), m_cards.end());
最后一个将使用operator==(const Card&, const Card&)
作为谓词
P.S. 上面的代码是在默认的 SO 文本编辑器中用心编写的,从未编译过。很抱歉可能有错别字。
相关文章:
- 嵌套在类中时无法设置成员数据
- 私有成员数据不可用于公共成员功能
- 我想知道我是否可以将一个类分配给特定的成员数据并创建该类的实例
- 类的成员数据未更新
- 为什么类成员数据必须是静态的才能被模板化类的模板化结构成员访问
- C++:成员不可访问-使用友元函数允许一个类修改另一个类的成员数据
- 如何高效更改向量中所有对象的成员数据?
- constexpr 偏移量,带有指向成员数据的指针
- 从其后声明的另一个成员数据初始化成员数据是否为未定义行为
- C++ 类析构函数删除部分但不是全部成员数据
- 初始化 MFC 中 CFormView 派生类的成员数据
- 覆盖复制/移动分配超载时,我是否需要删除当前的成员数据
- 根据参数设置构造函数的成员数据类型
- 对齐说明符:在类型 / 上 成员数据
- 如何实现ressize()以更改C 中动态成员数据的能力
- C++ 阻止复制成员数据
- 什么是成员数据指针的正确赋值语句
- C++ 在类中使用 strcmp() 处理私有成员数据
- 成员数据在stack实例上覆盖
- 初始化继承的成员数据