c++ - 在 map C++ 中使用数组作为键

标签 c++ arrays dictionary

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

abcdefg={1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}
aaaaaaa={7,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}

这就是我创建数组的方式。

//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;
}

这就是我在 map 中存储数组的方式。

dictionary[letters].push_back(stringtemp);

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

最佳答案

全部std::array<T, 26> , std::stringstd::vector<T>std::map 的完全有效的 key 类型,因为它们都定义了小于比较运算符。注意 std::array<T, 26>类似于 std::tuple<T, T, ..., T> , 比较是按字典顺序定义的,与字符串比较非常相似。

#include <array>
#include <map>

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

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

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

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

关于c++ - 在 map C++ 中使用数组作为键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12438602/

相关文章:

c++ - 使用声明实现这个抽象类

c++ - 指向存储在 map 容器中的数据的指针

python - 在 Python 的多个词典中搜索键的最佳方法是什么

python - 来自文件的动态字典

c++ - O'Reilly 的 "Objective-C Pocket Reference"声称 C++ 不支持动态调度,这是真的吗?

c++ - libc++:为什么关闭后流仍然很好

c++ - friend 类不适合我?

php - 根据最小值和最大值消除数组元素

arrays - 如何比较 BASH 中的数组元素?

Javascript 多个 IMG 数组