我把自己帶進了一個我不知道如何擺脫的兔子洞,我創造了一副隨機卡片。但是,我現在需要首先按西裝對它們進行排序,然后按我的列舉順序對它們進行排序。首先我不知道如何從向量和列舉中獲取元素,所以我可以比較它們,其次,我懷疑這個鏈接到第一個我不確定如何交換它們,最后會很好有一個冒泡排序的功能,我可以呼叫兩次以先按花色排序,然后再次呼叫以按卡片排序。
這里是圖書館:
#include <iostream>
#include <vector>
#include <cstdlib>
using namespace std;
using std::vector;
這些是結構和列舉:
enum Rank { ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE }; // aspects of the card
enum Suit { HEARTS, CLUBS, DIAMONDS, SPADES }; // suits of the card
struct Card { //Card data numbers
Rank rank;
Suit suit;
};
struct Deck { // defines a card
vector<Card> cards; // All the cards
int size = 5; // Max deck size
};
這是生成隨機卡片組的原因:
void initialize(Deck& deck, string stdno) {
for (int count=0; count < deck.size; count ) { //creates a deck of cards
Card card;
string rcardstr = stdno.substr(rand() % 8, 1) stdno.substr(rand() % 8, 1);
int rcard = stoi(rcardstr) % 52;
card.suit = static_cast<Suit>(rcard / 13); //cast between the enumerator and the value
card.rank = static_cast<Rank>(1 rcard % 13);
deck.cards.push_back(card); //Adds the card to the deck of cards
}
}
在我意識到我的前兩個問題之前,這是我對冒泡排序的微弱嘗試:
void bubble_sort(Deck& deck ){
bool swapp = true;
while (swapp) {
swapp = false;
for (int i=0; i < deck.size; i ) {
if (deck.rank[0]
}
}
}
...最后是我的主要功能:
int main() {
string stdno="14398132";
Deck my_deck;
initialize(my_deck, stdno);
}
If someone would be willing to give me a few minutes of their time to explain where I need to look/what I need to learn I would be incredibly grateful and make sure to give the same time back to the community once I've become better at c .
Solution: https://pastebin.com/j8ZwUaUX password: MrVolts thankyou Ari
uj5u.com熱心網友回復:
訪問deck成員的方法是這樣寫:
deck.cards[i].rank
要么
deck.cards[i].suit
您有多種排序選項。
- 簡單寫兩個函式:
void bubble_sort_by_rank(Deck& deck ){
bool swapp = true;
while (swapp) {
swapp = false;
for (int i=0; i < deck.cards.size()-1; i ) {
if (deck.cards[i 1].rank > deck.cards[i].rank){
//...
}
}
}
}
和
void bubble_sort_by_suit(Deck& deck ){
bool swapp = true;
while (swapp) {
swapp = false;
for (int i=0; i < deck.cards.size()-1; i ) {
if (deck.cards[i 1].suit > deck.cards[i].suit){
//...
}
}
}
}
撰寫一個冒泡排序函式,但將排序條件作為引數(可以是列舉)。
撰寫一個冒泡排序函式,但首先按花色比較每張卡片,如果它們相等,然后按等級比較它們,或者按照評論中的建議為您的卡片類多載 operator<。這可能是首選方法并且更有效。
如果您不堅持使用冒泡排序,您可以使用std::sortlambda 函式,該函式首先按花色比較您的牌,然后按等級比較。
對于交換,您應該能夠使用std::swap或自己撰寫一個簡單的模板函式:
template <class T>
void swap(T& x,T& y)
{
T temp;
temp=x;
x=y;
y=temp;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/444254.html
標籤:c enums bubble-sort
