C++ 使用数组作为映射C++;
基本上,我需要找到一个单词的所有匹配字谜。我所做的是使用一个大小为26的数组来表示单词中的字母。 例: 这就是我创建阵列的方式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
//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";