我应该为名人堂选择什么样的容器?
问题描述:
我有一个简单的问题。
具有这种特性的容器:
- 唯一键。
- 可以按照价值。
我正在尝试为我的项目实施名人堂部分。
对于每个条目,它需要一个字符串和一个整数(名称和分数)。
我尝试过:
我试过
I have a simple question.
What container that have this characteristic:
- Unique key.
- Can be sorted according to the value.
I'm trying to implement 'Hall of Fame' section to my project.
For each entry it require a string and an integer (name and score).
What I have tried:
I tried
std::map<std::string,unsigned int>
在我天真地实现的地图中,我发现它没有按值(整数)排序。
我该怎么办?我应该把它交换成
In my naively implemented map, I found that it is not sorted by the value (integer).
What should I do? should I just swapped it to become
<unsigned int, std::string>
但它不处理唯一键(名称)。
请教我如何。
But it doesn't handle unique keys (name).
Please, teach me how.
答
据我所知没有这样的容器。一个简单的解决方案,如果数据大小不大,将使用两个容器:map< string,>
(或unordered_map< string, >
)和map< int,>
,但是你必须确保它们保持同步。
In my knowledge there is no such a container. A simple solution, if data size isn't huge, would be using both the containers:map<string,>
(orunordered_map<string,>
) andmap<int,>
, however then you must be sure to keep them in sync.
C ++标准库使用的第一条规则是获取向量
并使用它。只有当它太慢(或者你没有足够的连续地址空间)时,你还要去另一个容器。
所以试试std :: vector< std :: pair xmlns:std =#unknown>< std :: string,>>< / std :: pair>
明智地使用std :: sort
和std :: find
订购你的价值并找到具体的价值。
The first rule of C++ standard library use is grab avector
and use that. Only if that's too slow (or you don't have enough contiguous address space) do you bother reaching for another container.
So trystd::vector<std::pair xmlns:std="#unknown"><std::string,>></std::pair>
stirred with a judicious use ofstd::sort
andstd::find
to order your values and find specific values.