簡體   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