创建一个可以接收 board1[{1,1}]='X'; 的类; ?(方括号内的大括号)

creating a class that can receive board1[{1,1}]='X'; ? (curly brackets inside square brackets)

本文关键字:的类 方括号 一个 创建 board1      更新时间:2023-10-16

我得到了H.W.,在main的一行中.cpp我应该支持:

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

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

我该怎么做?

附言 由于这些是符号而不是字符(并且由于我不认识属于此问题的任何术语(,因此在Google中搜索此类问题非常困难,因此这可能是重复的:-(,希望不是。

我尝试做:

第一次尝试:

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

你需要做这样的事情:

struct coord {
int x;
int y;
};
class whatever
{
public:
//data being what you have in your board
data& operator[] (struct coord) {
//some code
}
};

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

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