按字符串而不是整数值编制索引的矩阵

Matrix indexed by strings instead of integer values

本文关键字:索引 字符串 整数      更新时间:2023-10-16

是否可以在C++中拥有一个整数值矩阵,我可以通过字符串索引访问这些值?做类似 M["一"]["二"]++ 的事情;等。

使用unordered_map(在增强或c++11中)或只是在良好的旧C++中使用map。做一个unordered_map<string, unordered_map<string, int> >。应该做这个伎俩。

我会将内部细节与用户界面分开。

例如,如果您想使用其他语言怎么办?

有一个从单词到整数的映射:

map<string, unsigned int> index;
index["one"] = 1;
// .etc

像往常一样在 2D 数组上使用整数。

int x = index["one"];
int y = index["two"];
doSomething(array[x][y]);

这不是直接的,但既然你问了,你可能不知道operator []().您可以定义自定义[]运算符。

只是为了向您解释背后的概念:您可以定义一个拥有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;