简体   繁体   中英

Why isn't my less-than operator processing?

I just starting programming, just about a week ago, and I wanted to try and make a Blackjack game.

I wanted to run code using a while loop, while both hands are less than 21, run some code.

Simple enough.

But, for some reason, the less-than operator isn't working.

Here's the error message:

C2676 binary '<': 'std::vector<int,std::allocator<int>>' does not define this operator or a conversion to a type acceptable to the predefined operator

Can someone help me fix this?

Here's my code:

#include <iostream>
#include <vector>

std::vector<int> handone(0);
std::vector<int> handtwo(0);

int main() {
    while (handone < 21 && handtwo < 21) {
    }
}

The error message is telling you that std::vector does not implement an operator< that takes an int as input. Which is true, as it only implements anoperator< to compare against another vector instead.

Assuming your vector s contain the values of individual cards, you will need to sum the values manually, such as with the standard std::accumulate() algorithm, eg:

#include <iostream>
#include <vector>
#include <algorithm>

std::vector<int> handone;
std::vector<int> handtwo;

int valueOfHand(const std::vector<int> &hand) {
    return std::accumulate(hand.begin(), hand.end(), 0);
}

int main() {
    while (valueOfHand(handone) < 21 && valueOfHand(handtwo) < 21) {
        ...
        handone.push_back(...);
        handtwo.push_back(...);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM