std :: find使用用户定义的struct [duplicate]

问题描述 投票:1回答:1

这个问题在这里已有答案:

我试图在标准的52卡片组中找到5张牌的所有可能组合。我想我差不多了,但是我被卡在一个特定的if语句上。我试图弄清楚一个数组是否已经在一个向量中,如果不是我添加它

if (std::find(combos.begin(), combos.end(), combo) != combos.end()){
    std::cout << combos.size() << endl;
    continue;
}
std::cout << combos.size() << endl;
combos.push_back(combo);

组合是std::vector<std::array<card, 5>>和组合是std::array<card, 5>。我用g ++得到以下错误

/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/algorithm:677:71: error: 
  invalid operands to binary expression ('const card' and 'const card')
bool operator()(const _T1& __x, const _T1& __y) const {return __x == __y;}

card是一个看起来像这样的结构

struct card {
    Suit suit;
    int rank;
};

我只是不知道该怎么做。谢谢你的任何想法

c++ c++11 std
1个回答
3
投票

“只是”就像错误消息所说,你需要为你的card类实现一个相等运算符。

bool operator == (const card &lhs, const card &rhs) // with or without the ref & symbol
{
    return lhs.suit == rhs.suit && lhs.rank == rhs.rank;
}

作为一个侧面问题,卡的数量超过250万,并且算法以O(n ^ 2)运行,因此您可能看不到它在任何合理的时间范围内完成。

© www.soinside.com 2019 - 2024. All rights reserved.