创建一个可以接收 board1[{1,1}]='X'; 的类; ?(方括号内的大括号)
creating a class that can receive board1[{1,1}]='X'; ? (curly brackets inside square brackets)
我得到了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 的答案更正。
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- std::具有相同基类的类的变体
- 命名空间中具有.h和.cpp文件的类
- 设计一个只能由特定类实例化的类(如果可能的话,通过make_unique)
- 当函数模板参数是具有默认参数的类模板时,函数模板参数的推导如何执行
- 如何从具有移动语义的类对象中生成共享指针
- 如何将参数传递给正在使用模板的类
- 如何制作一个将函数作为参数的类方法
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 在 .h 文件中的类中声明静态变量和在.cpp文件中声明"global"变量有什么区别
- 模板化的类和友元函数
- 从类继承时,继承的类是否会通过父类重新定义继承的变量
- 如何在C++中获取该对象的类声明中对象的地址?
- 在std::vector上存储带有模板的类实例
- 如何在c++中定义以struct为数据成员的类中的构造函数
- 为什么C++编译器没有检测到正确声明的类?
- 如果C++对象的类在另一个boost模块中声明,如何使用boost将指向该对象的指针返回到python
- 具有包含其他对象的类的对象创建顺序
- 删除C++中带有 vector<const char *> 的类
- 创建一个可以接收 board1[{1,1}]='X'; 的类; ?(方括号内的大括号)