在 C++ 中是否有可能有一个 int 值矩阵,我可以通过字符串索引访问这些值?做类似 M["one"]["two"]++; 等等
3 回答
4
使用unordered_map(在 boost 或 中c++11)或只是map在 good old 中使用C++。做一个unordered_map<string, unordered_map<string, int> >. 应该做的伎俩。
于 2013-01-25T14:48:49.653 回答
0
这不是直接的,但既然你问了,你可能不知道operator [](). 您可以定义您的自定义[]运算符。
只是为了向您解释背后的概念:您可以定义一个类 Row 或 Column,拥有一个std::vector<int>. 对于此类,您可以定义operator[]:
class Row
{
public:
int& operator[](const std::string& );
//...
std::vector<int> ints;
}
您的班级矩阵将拥有一个std::vector<Row>
class Matrix
{
public:
Row& operator[](const std::string& );
//...
std::vector<Row> rows;
}
这将使您能够使用语法Matrix m; m["one"]["two"]=2;
于 2013-01-25T14:55:09.343 回答
0
我会将内部细节与用户界面分开。
What if you want to use a different language, for example?
Have a map from the word to the integer:
map<string, unsigned int> index;
index["one"] = 1;
// .etc
Use the integer on a 2D array, as normal.
int x = index["one"];
int y = index["two"];
doSomething(array[x][y]);
于 2013-01-25T15:06:27.297 回答