1

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) {
    }
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 4
    you are comparing a vector with an integer. This obviously will not work. You need an index into the vector which will extract the integer within the vector, which can then be compared. – user3389943 May 28 '21 at 17:30
  • 3
    C++ doesn't just automatically understand that you want to sum the contents of vector. You need to tell it to do so. There are multiple ways that can be done. Googling "c++ sum contents of vector" will probably be educational. – TheUndeadFish May 28 '21 at 17:40
  • Thank you so much for the clarification! – Maxon Baisley May 28 '21 at 17:53
  • 1
    Here's some ways to sum a vector: [How to sum up elements of a C++ vector?](https://stackoverflow.com/questions/3221812/how-to-sum-up-elements-of-a-c-vector), which you can then compare in your `while` condition. – zcoop98 May 28 '21 at 17:54

1 Answers1

3

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 an operator< to compare against another vector instead.

Assuming your vectors 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(...);
    }
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770