我想更换一个 vector<string>
和一个 boost::unordered_map<string, size_t>
使用 boost::bimap
将字符串映射到前者的索引.
bimap
的实例化是什么?我应该使用吗?到目前为止,我想出了
typedef bimap<
unordered_set_of<size_t>,
vector_of<string>
> StringMap;
但我不确定我现在是否已经颠倒了集合类型。另外,我想知道我是否应该更改 collection of relations type .会 vector_of_relation
是我最好的选择,或者set_of_relation
,还是只使用默认值?
最佳答案
要获得 size_t 和 std::string 之间的 bimap,其中您有 ~constant(取决于散列成本和任何潜在的冲突),您需要使用 unordered_set_of:
#include <boost/bimap.hpp>
#include <boost/bimap/unordered_set_of.hpp>
#include <string>
#include <iostream>
#include <typeinfo>
int main(int argc, char* argv[]) {
typedef boost::bimap< boost::bimaps::unordered_set_of<size_t>, boost::bimaps::unordered_set_of<std::string> > StringMap;
StringMap map;
map.insert(StringMap::value_type(1,std::string("Cheese")));
map.insert(StringMap::value_type(2,std::string("Cheese2")));
typedef StringMap::left_map::const_iterator const_iter_type;
const const_iter_type end = map.left.end();
for ( const_iter_type iter = map.left.begin(); iter != end; iter++ ) {
std::cout << iter->first << " " << map.left.at(iter->first) << "\n";
}
}
返回:
1 Cheese
2 Cheese2
unordered_set 是 set 的 boost 版本,它使用哈希表而不是树来存储元素,参见 Boost Unordered docs .
查看来自 Bimap example 的一个双图示例的评论,我们有:
The left map view works like a std::unordered_map< std::string, long >, given the name of the country we can use it to search for the population in constant time
关于c++ - 用 Boost.Bimap 替换 vector 和哈希表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4194468/