C ++中向量的哈希表 [英] Hashmap of Vectors in C++

查看:98
本文介绍了C ++中向量的哈希表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在C ++中实现一个向量hashmap。这是我的代码:

I want to implement a hashmap of vectors in C++. Here is my code:

#include <cstdlib>
#include <string>
#include <iostream>
#include <vector>
using namespace std;

#include <ext/hash_map>
using namespace __gnu_cxx;

int main (int argc, char * const argv[]) {
    std::vector<int> v;
    hash_map<int, std::vector<int> > months;
    v.push_back(28);
    v.push_back(28);
    v.push_back(28);
    v.push_back(29);
    months["february"] = v; //error = invlalid conversion from const char* to int
    return 0;
}

上面的代码无法编译。相关行旁边包含错误。它与我有什么关系,而忽略了可选参数的值(散列和比较)吗?

The above code fails to compile. Errors included next to relevant lines. Does it have anything to do with me leaving out values for the optional arguments (hash and comparison)?

推荐答案

其他答案都是一样的。有一个固定的月数。没有必要通过字符串来存储它们。一个枚举可以帮助你通过名字来引用它们。这样会更有效率,但不是预先优化,因为它也更有意义。像字符串版本中的feburary这样的错字将会增加一个新的月份!如果它是一个 enum ,你会得到一个编译错误,再加上如果你的编辑器使用自动完成功能,你将不必查找如何拼写杂志。

Different than the 5 other answers that are all the same. There are a fixed number of months. It would be unnecessary to store them by a string. An enum could help you refer to them by name. This would be much more efficient, but not a pre-optimization, because it also makes more sense. A typo like "feburary" in the string version would add a new month! If it were an enum you would get a compile error, plus if your editor uses auto-completion, you won't have to look up how to spell februrary.

enum { JANUARY=0, FEBRUARY,MARCH,APRIL,MAY,JUNE,JULY,AUGUST,SEPTEMBER,OCTOBER,NOVEMBER,DECEMBER};
months[FEBRUARY] = v; 

如果您不想污染全局域名,您可以将它放在名称空间中。在这一点上让它们小写更容易。

You could place it in a namespace if you didn't want to pollute the global one. And it would be easier to make them lowercase at this point.

namespace Month {
enum { January=0, February,March,April,May,June,July,August,September,October,November,December};
}
months[Month::February] = v; // equivalent to months[1]=v if you prefer number

你也可以开始 enum 为1,如果你想让1月份保持为1而不是2月份。这对你更有意义。我认为大众应该把1月份称为0,但也许这就是我。 0可以更改为NULL_MONTH或INVALID_MONTH,或适合您的设计。

You could also start the enum at 1 if you wanted to keep January being 1 instead of February. That may make more sense to you. I think the general public should refer to January as 0, but maybe that's just me. The 0 could be changed to NULL_MONTH or INVALID_MONTH, or whatever fits your design.

这篇关于C ++中向量的哈希表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆