0

我正在处理一项任务,我们必须对可以使用向量相互交互的多副牌进行编程(例如,从主牌组中移除一张牌并将其添加到另一张牌中)。赋值声明我们必须使用卡片结构中的重载“小于”运算符,通过将其与 std::lower_bound 函数组合来确定卡片的正确顺序。到目前为止,这就是我所拥有的:

void CardDeck::Add(const Card& card)
{
    m_Cards.insert(std::lower_bound(m_Cards.begin(),m_Cards.end(),card,*insert smaller than operator here*),card);
}

Card 结构的重载“小于”运算符如下。它根据枚举中的预定顺序比较卡片的等级和花色:

friend bool operator< (const Card& lhs, const Card& rhs)
{
    if(lhs.m_Suit < rhs.m_Suit || (lhs.m_Suit == rhs.m_Suit && lhs.m_Rank < rhs.m_Rank))
    {
        return true;
    }
}

任何帮助是极大的赞赏。赋值声明我们必须使用重载运算符。我们不允许自己创建一个简单的“IsSmallerThan()”方法。

非常感谢。

编辑:忘记标记问题。评论中的额外信息。

4

2 回答 2

2

By default, std::lower_bound uses the less-than operator for the type behind the iterators. By defining your own operator <, lower_bound should just do the right thing. i.e. calling it like this

std::lower_bound(m_cards.begin(), m_cards.end(), card);

should work fine, give an appropriate operator < defined on card types.

One thing to point out is your code for operator < can be simplified to

friend bool operator< (const Card& lhs, const Card& rhs)
{
   return lhs.m_Suit < rhs.m_Suit || 
       (lhs.m_Suit == rhs.m_Suit && lhs.m_Rank < rhs.m_Rank);
}

(which also fixes a subtle bug in your code).

于 2013-10-31T17:14:38.833 回答
1

You need

void CardDeck::Add(const Card& card)
{
    m_Cards.insert(std::lower_bound(m_Cards.begin(),m_Cards.end(),card,std::less<Card>()),card);
}

if you want to really provide a comparator. Since the default is already to use the above, you can also simply leave it out:

void CardDeck::Add(const Card& card)
{
    m_Cards.insert(std::lower_bound(m_Cards.begin(),m_Cards.end(),card),card);
}

You can also simplify your operator< (and make it less error-prone) by using std::tie:

friend bool operator< (const Card& lhs, const Card& rhs)
{
    return std::tie(lhs.m_Suit, lhs.m_Rank) < std::tie(rhs.m_Suit, rhs.m_Rank);
}
于 2013-10-31T17:13:58.710 回答