簡體   English   中英

有沒有辦法在 C++ 中創建一個循環數組

[英]Is there a way to create a looped array in c++

好的,所以我有一個問題,我懷疑它是否是一個實際的 c++ 功能,但值得一試......我正在創建一個基於終端文本的 mancala 游戲,我正在使用一個數組來跟蹤棋盤上每個杯子的點數,我想知道如果用戶觸發“boardArray[13]”杯子,並且數組的流動是按時間順序進行的,我想知道是否有任何方法“boardArray[13]”循環回到棋盤的開頭,並開始分配回“boardArray[1]”。 我懷疑這是否有意義,如果您需要我澄清,請告訴我。 我基本上想要一個數組

1,2,3,4,5,6,7,8,9,10,11,12,13,14, RESET 
1,2,3,4,5,6,7,8,9,10,11,12,13,14, RESET
1,2,3...

內置數組類型不會這樣做。 如果您願意,可以很容易地創建一個帶有重載運算符的類型來完成這項工作。

template <std::size_t N>
class LoopedArray {
    int data[N];
public:
    int &operator[](size_t index) { 
        return data[index % N];
    }
};

int main() {
    LoopedArray<13> la;

    // put known values into the array:
    for (int i=0; i<13; i++)
        la[i] = i;

    // demonstrate reading the data with "looping" of the index:
    for (int i=0; i<100; i++)
        std::cout << la[i] << "\t";
}

我是否真的建議這樣做還有更多問題,但它肯定可以完成,我想我可以相信它可能有用......

為此,您不需要“循環數組”,據我所知,C++ 中不存在這樣的東西。

您可以通過循環索引來輕松實現相同的效果。

而不是使用yourArray[i]只需使用yourArray[i%14]只訪問它的前 14 個元素。

我知道的 C++ 中不存在這樣的數組(或與此相關的所有編程)。

你可以嘗試的是一個鏈表:

class node {
public:
    node* next;
    int value;

}

然后,將幾個鏈接在一起:

node root;
node* current=&root
for(i=0;i<14;i++) {
    current->value=0; // for initialization
    current->next = new node;
    current = current->next;
}
current->next = root;

這些項目將循環鏈接。 您可以像這樣訪問它們

int value = current->value;
for(int i=0;i<value;i++) {
    current = current->next;
    current.value +=1;
}

當然,這會變得非常混亂,尤其是當您嘗試刪除它時。

void DeleteList(node *n,node *root) {
    if(n == root) {
        return;
    }
    DeleteList(n->next,root);
    delete n;
}

這只是一個例子,但它可能很快就會出現很多問題。

我想我真正應該推薦的內容類似於AlbertM 推薦的內容,但為您提供了一個很好的功能:

void addPoints(int arr[], int cup, int arrlen) {
    int value = arr[cup]; // stored for later    
    arr[cup] = 0; // since we are emptying the cup

    for(int i=0; i<value;i++) {
        arr[(cup+i)%arrlen] += 1;
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM