繁体   English   中英

为什么我的小于运算符没有处理?

[英]Why isn't my less-than operator processing?

大约一周前,我刚开始编程,我想尝试制作二十一点游戏。

我想使用while循环运行代码,而双手小于21,运行一些代码。

很简单。

但是,由于某种原因,小于运算符不起作用。

这是错误消息:

C2676 二进制 '<': 'std::vector<int,std::allocator<int>>' 未定义此运算符或转换为预定义运算符可接受的类型

有人可以帮我解决这个问题吗?

这是我的代码:

#include <iostream>
#include <vector>

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

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

错误消息告诉您std::vector没有实现将int作为输入的operator< 这是真的,因为它只实现了一个operator<来与另一个vector进行比较。

假设您的vector s 包含单个卡片的值,您将需要手动对这些值求和,例如使用标准std::accumulate()算法,例如:

#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(...);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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