簡體   English   中英

我不能不使用指針返回二維數組! 我正在制作一個井字游戲,這是我的向上移動功能

[英]I cant return a 2d array without using pointers ! im making a tic tac toe type game and this is my move up function

char[][]  moveup()
{
for (int i=0;i<3;i++)
 {
for (int j=0;j<3;j++)
  {

   if(board[i][j]=='X' && board [i-1][j]=='!' ) {
    board [i][j]='!';
    board [i-1][j]='X';
    }
   }
   }
    return board;
  }

這是我的代碼,我想將這個二維數組傳遞給一個向量,所以我想在不使用指針的情況下返回一個二維數組板

傳入向量並在此函數中填充它。

您可以返回對數組的引用:

char(&moveup())[3][3]
{
    for (int i=0; i<3; i++) {
        for (int j=0; j<3; j++) {

            if (board[i][j]=='X' && board[i-1][j]=='!') {
                board[i][j]='!';
                board[i-1][j]='X';
            }
        }
    }
    return board;
}

這是一個通過引用傳遞數組的完整程序。 注意我們現在如何使用基於范圍的 for 循環來迭代元素,因為引用沒有衰減到指針並且維度和類型被保留:

#include <iostream>
#include <vector>

class Board {

public:
    char(&moveup())[3][3]
    {
        for (int i=0; i<3; i++) {
            for (int j=0; j<3; j++) {

                if (board[i][j]=='X' && board[i-1][j]=='!') {
                    board[i][j]='!';
                    board[i-1][j]='X';
                }
            }
        }
        return board;
    }

    char board[3][3];
};



int main()
{
    Board board{
        '.','!','x',
        'o','X','x',
        '.','o','x'
    };

    auto& sameboard = board.moveup();

    for (auto& row : sameboard) {
        for (auto& element : row) {
            std::cout << element;
        }
        std::cout << '\n';
    }

    return 0;
}

暫無
暫無

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

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