按字符串而不是整数值编制索引的矩阵
Matrix indexed by strings instead of integer values
是否可以在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;
相关文章:
- 按字母顺序对C++问题中的子字符串索引进行分区
- C++ 中字符串向量的索引
- C++ - 成功打印超出范围的字符串索引
- 对于循环增量器不能用作字符串向量的索引
- 如何检索由带通配符的字符串索引的对象
- 访问包含P的有效索引时返回空格的C++字符串
- 在我的 for 循环中,如何将索引更改为字符串?
- "如何使用C++将字符串的第一个和最后一个索引返回到向量中?
- C++ 复制字符串的指定索引之间的任何子字符串
- 查找C++中两个索引之间的子字符串
- 具有二叉索引树的字符串查询
- 有效地从文本文件中读取带有字符串索引的大型二维数组(矩阵)
- 尝试查找从索引 0 开始的偶数长度子字符串
- 如何根据某个索引将字符串与正则表达式匹配?
- 为字符串中的每个字符(不是字符位置!)分配唯一的索引
- 通过字符串的字符对整数数组进行索引
- 从给定索引返回子字符字符串的函数
- 此代码如何启动索引为 1 的 C 样式字符串
- 如何使用二叉搜索返回姓氏(给定字符串)的第一个索引/出现次数?
- 索引c++字符串的最简单方法