简体   繁体   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;
  }

This is my code and I want to pass this 2d array then in to a vector so i want to return a 2d array board without using pointers这是我的代码,我想将这个二维数组传递给一个向量,所以我想在不使用指针的情况下返回一个二维数组板

传入向量并在此函数中填充它。

You could return a reference to the array:您可以返回对数组的引用:

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;
}

Here is a full program passing the array by reference.这是一个通过引用传递数组的完整程序。 Note how we can now use a range based for loop to iterate over the elements because the reference hasn't decayed to a pointer and the dimensions and type is preserved:注意我们现在如何使用基于范围的 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