【问题标题】:Matrix indexed by strings instead of integer values由字符串而不是整数值索引的矩阵
【发布时间】:2013-01-25 14:46:50
【问题描述】:

在 C++ 中是否有可能有一个 int 值矩阵,我可以通过字符串索引访问这些值?做类似 M["one"]["two"]++;等等

【问题讨论】:

  • 你可以使用地图 >
  • @Mordachai 我如何迭代地图的值 > M; ?
  • 您将使用嵌套循环,就像您可能会使用矩阵一样:for(auto outter = matrix.begin(); outter != matrix.end(); ++outter) for (auto inner = outter.begin(); inner != outter.end(); ++inner) { /* do whatever you want with *inner */ }

标签: c++ string map stl matrix


【解决方案1】:

使用 unordered_map(在 boost 或 c++11 中)或在旧的 C++ 中使用 map。制作unordered_map<string, unordered_map<string, int> >。应该做的伎俩。

【讨论】:

  • 是否可以只使用 map > M;并在不遍历地图的情况下将 M 的所有值初始化为 0?
  • 我如何迭代地图的值 > M; ?
  • @shn 使用迭代器:for (map<string, map<string, int> >::iterator it = M.begin(); it != M.end(); ++it)
  • 最好使用std::map<std::pair<std::string, std::string>, int>,但这样语法就不会那么漂亮了。
  • @Zyx2000 为什么你认为它会更好?
【解决方案2】:

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

例如,如果您想使用不同的语言怎么办?

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

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

像往常一样在二维数组上使用整数。

int x = index["one"];
int y = index["two"];

doSomething(array[x][y]);

【讨论】:

    【解决方案3】:

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

    只是为了向您解释背后的概念:您可以定义一个类 Row 或 Column,拥有一个 std::vector&lt;int&gt;。对于此类,您可以定义 operator[]:

    class Row
    {
    public:
        int& operator[](const std::string& );
        //...
        std::vector<int> ints;
    }
    

    你的班级矩阵将拥有一个std::vector&lt;Row&gt;

    class Matrix
    {
    public:
        Row& operator[](const std::string& );
        //...
        std::vector<Row> rows;
    }
    

    这将使您能够使用语法Matrix m; m["one"]["two"]=2;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-07
      • 1970-01-01
      • 2013-12-16
      相关资源
      最近更新 更多