[英]Matrix indexed by strings instead of integer values
Is it possible in C++ to have a matrix of int values where I can access to these values through string indexes ? 在C ++中是否可以有一个整数值矩阵,可以在其中通过字符串索引访问这些值? Doing something like M["one"]["two"]++;
做类似M [“ one”] [“ two”] ++的事情; etc.
等等
Use unordered_map
(in boost or c++11
) or just map
in good old C++
. 使用
unordered_map
(在boost或c++11
)或仅在旧的C++
map
。 Make a unordered_map<string, unordered_map<string, int> >
. 制作一个
unordered_map<string, unordered_map<string, int> >
。 Should do the trick. 应该做到的。
It's not direct, but since you ask, you probably don't know about operator []()
. 它不是直接的,但是既然您问,您可能不知道
operator []()
。 You can define your custom []
operator. 您可以定义自定义
[]
运算符。
Just to explain you the concept behind: you could define a class Row, or Column, owning a std::vector<int>
. 只是为了向您解释背后的概念:您可以定义一个类Row或Column,并拥有一个
std::vector<int>
。 For this class you could define the operator[]
: 对于此类,您可以定义
operator[]
:
class Row
{
public:
int& operator[](const std::string& );
//...
std::vector<int> ints;
}
Your class matrix then would own a std::vector<Row>
然后,您的类矩阵将拥有一个
std::vector<Row>
class Matrix
{
public:
Row& operator[](const std::string& );
//...
std::vector<Row> rows;
}
this would enable you to use the syntax Matrix m; m["one"]["two"]=2;
这将使您能够使用语法
Matrix m; m["one"]["two"]=2;
Matrix m; m["one"]["two"]=2;
I would keep internal details separate from the user interface. 我会将内部细节与用户界面分开。
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. 照常在2D数组上使用整数。
int x = index["one"];
int y = index["two"];
doSomething(array[x][y]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.