Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/130.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用数组作为映射C++;_C++_Arrays_Dictionary - Fatal编程技术网

C++ 使用数组作为映射C++;

C++ 使用数组作为映射C++;,c++,arrays,dictionary,C++,Arrays,Dictionary,基本上,我需要找到一个单词的所有匹配字谜。我所做的是使用一个大小为26的数组来表示单词中的字母。 例: 这就是我创建阵列的方式 //stringtemp is a C++ string representing the word. //letters is a size 26 int array representing all the letters in the string. for(int i=0;i<stringtemp.length();i++) { letters[s

基本上,我需要找到一个单词的所有匹配字谜。我所做的是使用一个大小为26的数组来表示单词中的字母。 例:

这就是我创建阵列的方式

//stringtemp is a C++ string representing the word.
//letters is a size 26 int array representing all the letters in the string.
for(int i=0;i<stringtemp.length();i++)
{
    letters[stringtemp[i]-65]+=1;
}

>我是不是做了什么错事,或者C++里是不可能的。在我找到的所有其他答案中,他们建议使用向量作为键,但这在我的情况下不起作用(我认为)。

映射中的键类型必须有一个
操作符所有
std::array
std::string
std::vector
都是
std::map
的完全有效的键类型,因为它们都定义了小于比较运算符。请注意,
std::array
类似于
std::tuple
,比较是按词典定义的,非常类似于字符串比较

#include <array>
#include <map>

typedef std::array<unsigned int, 26> alphabet;

std::map<alphabet, std::string> dictionary;

dictionary[{{1, 0, ..., 8}}] = "hello";
#包括
#包括
typedef std::数组字母表;
地图词典;
字典[{{1,0,…,8}}]=“你好”;

通过更多的工作,您还可以为
std::unordered_map
创建所有这些类型的键,尽管您必须从Boost中添加一些样板代码(使用
hash_combine
)。

允许您在构造函数中提供一个比较运算符。您可能需要提供这样一个比较器,以便两个数组{1,…..}和{1,…..}匹配,因为它们可能是不同的实际对象。

如下所示,C样式数组不会像您期望的那样进行复制。包括
字典
字母
的定义会有所帮助。
std::string
并不是真正的密钥类型。@LucDanton:
string
将在紧急情况下完成复制,并且它是唯一一种定义了现成哈希函数的类型。因此,如果哈希表在计算上是必不可少的,那么使用字符串要比在向量上定义自己的哈希操作更容易。否则你当然有一个正确的观点。当我尝试的时候,我会得到一个正确的答案“@user1525047之前需要初始值设定项:
std::array
需要C++11支持。在GCC中,将
-std=c++0x
添加到编译器命令中。或者,使用
std::tr1::array
。但是,一个由12000个
'A'
组成的字符串将非常低效。
dictionary[letters].push_back(stringtemp);
#include <array>
#include <map>

typedef std::array<unsigned int, 26> alphabet;

std::map<alphabet, std::string> dictionary;

dictionary[{{1, 0, ..., 8}}] = "hello";