4

我在 main.cpp 的其中一行中得到了硬件,我想支持:

board1[{1,1}]='X';

这背后的逻辑意义是将(1,1)位置的字符“X”分配给“游戏板”。我不知道如何创建一个接收大括号的数组,例如 [{int,int}]。

我怎样才能做到这一点?

PS因为这些是符号而不是字符(并且因为我不认识属于这个问题的任何术语)在谷歌中搜索这种类型的问题非常困难,所以这可能是重复的:-(,希望不是。

我试着做:

第一次尝试:

vector<vector<int> > matrix(50);
for ( int i = 0 ; i < matrix.size() ; i++ )
    matrix[i].resize(50);
matrix[{1,1}]=1;

第二次尝试:

int mat[3][3];
//maybe map
mat[{1,1}]=1;

第三次尝试:

class _mat { // singleton
    protected:
       int i ,j;

    public:
        void operator [](string s)
        {
            cout << s;
        }
};

_mat mat;
string s = "[{}]";
mat[s]; //this does allow me to do assignment also the parsing of the string is a hustle
4

2 回答 2

7

您需要执行以下操作:

    struct coord {
        int x;
        int y;
    };

    class whatever
    {
        public:
            //data being what you have in your board
            data& operator[] (struct coord) {
                //some code
            }
    };
于 2018-05-02T09:08:20.747 回答
2

你的第一次尝试,实际上非常接近工作。问题是向量的 [] 运算符将整数索引放入要更改的向量中的位置(并且向量必须足够大才能存在)。但是,您想要的是地图;这将创建该项目并为您分配它。因此,astd::map<std::vector<int>, char>会得到你想要的。(尽管它可能没有最好的性能)。

您的第二次尝试失败的原因与第一次相同(索引必须是整数),第三次由 Tyker 的回答纠正。

于 2018-05-02T09:58:15.970 回答