【问题标题】:Is it possible for the Keys of a map to be arrays? (Map array error)地图的键可以是数组吗? (映射数组错误)
【发布时间】:2015-12-21 04:31:32
【问题描述】:

我想制作一个地图,其中包含 int[27] 形式的数组作为键,所以我尝试了以下方法:

#include <map>
using namespace std;
map<int[27] ,int> mapa;
int n[27];
int main(){
    mapa[n]++;
}

但我得到一个错误,是因为数组不能用作地图的键类型吗?
在这种情况下我能做什么?如果我使用向量而不是数组,它会起作用吗?


这是建议吗?

#include <cstdio>
#include <map>
using namespace std;
map<array<int,27> ,int> mapa;
int n[27];
int main(){
    mapa[n]++;
}

这是有效的版本:

#include <cstdio>
#include <map>
#include <array>
using namespace std;
map<array<int,27>, int> mapa;
array<int,27> v;
int main(){
    mapa[v]++;
    printf("%d\n",mapa[v]);
}

【问题讨论】:

  • 改用map&lt;std::array&lt;int,27&gt; ,int&gt; mapa;
  • 它说mapa没有在这个范围内声明。
  • 添加#include &lt;array&gt;

标签: c++ arrays dictionary key


【解决方案1】:

但我得到一个错误,是因为数组不能是地图吗?

我认为您实际上是指映射键类型。不,原始数组不能用作键,因为没有为它们声明内在的 less 运算符。

在这种情况下我该怎么办?如果我使用向量而不是数组,它会起作用吗?

是的,您可以使用std::vector&lt;int&gt; 作为密钥。更好的是 std::array&lt;int,27&gt;,如果你知道它是 27 的固定大小。

std::less() 如何与std::array 协同工作的确切文档可以在here 找到。

您也可以像@NathanOliver 指出的那样提供自己的比较算法。


这是建议吗?

#include <cstdio>
#include <map>
using namespace std;
map<array<int,27> ,int> mapa;
int n[27];
int main(){
    mapa[n]++;
}

几乎。你需要

std::array<int,27> n;

当然,没有自动转换。

【讨论】:

  • 非常感谢!但是,当我运行我最近添加到问题正文中的代码时,它在 mapa[n]++ 行中标记了一个错误,说 mapa 未在此范围内声明,可以修复吗?
  • 看我对你的问题的评论,当然你必须包含相应的标题。
  • 好的,我已经开始工作了,我还有几个问题,谢谢你的帮助,太棒了。所以显然我现在正在使用不同类型的数组?为了让它工作,我必须使 n 成为一个新类型的数组。
  • 我上传了可以使用的最终版本,当我使用 int n[27] 时它不起作用。我必须声明一个数组类型的新对象,它们是不同的东西吗?此外,我必须使用修改后的 g++ 进行编译。这些对象只存在于 c++11 中吧?
  • 我已经在回答中指出,没有自动转换,你需要它。
【解决方案2】:

这将编译:

map<int *,int> mapa

但这不是你想要的...... 数组与指针几乎相同,因此您无法构建数组映射。它只会在检索/设置它的值时比较内存中的指针,而不是它的内容。

【讨论】:

  • @MtCS "...因此你无法构建数组映射。" 好吧,这里证明你错了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-09
  • 2019-12-07
  • 2017-01-20
  • 2020-11-05
  • 2021-10-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多