重复键的bimmap用法
bimap usage for repeated keys
根据这个问题中使用boost::bimap的建议,我有一个关于如何解决bimap中重复键的问题。
如果有:<key1, value1>, <key1, value2>
,是否可以在bimap中插入两次?
我看到了描述CollectionType_of的页面,默认类型是bimap< CollectionType_of<A>, CollectionType_of<B> >
的集合。所以两边的键都是唯一的。更重要的是,我想知道是否有更好的方法来快速找到value1 value2为key1 ?但是key1不是很好,因为用值作为键进行搜索。
谢谢你的建议!
您的案例需要一个自定义容器。它会有两个std::map<string, std::set<string>>
的映射。像这样:
template <typename K, typename V>
class ManyToManyMap
{
public:
typedef std::set<K> SetOfKeys;
typedef std::set<V> SetOfValues;
typedef std::map<K, SetOfValues> KeyToValuesMap;
typedef std::map<V, SetOfKeys> ValueToKeysMap;
private: // I usually put this to the bottom. But it's here for readability.
KeyToValuesMap keyToValues;
ValueToKeysMap valueToKeys;
public:
/* I leave it to requester to implement required functions */
void insert(const K& key, const V& value)
{
keyToValues[key].insert(value);
valueToKeys[value].insert(key);
}
void removeKey(const K& key)
{
KeyToValuesMap::iterator keyIterator = keyToValues.find(key);
if (keyToValues.end() == keyIterator) {
return;
}
SetOfValues& values = keyIterator->second;
SetOfValues::const_iterator valueIterator = values.begin();
while (values.end() != valueIterator) {
valueToKeys[*valueIterator++].remove(key);
}
keyToValues.erase(keyIterator);
}
/* Do the reverse for removeValue() - leaving to OP */
SetOfValues getValues(const K& key) const
{
KeyToValuesMap::const_iterator keyIterator = keyToValues.find(key);
if (keyToValues.end() == keyIterator) {
return SetOfValues(); // Or throw an exception, your choice.
}
return keyIterator->second;
}
/* Do the reverse for getKeys() - leaving to OP */
};
的用法类似于:
typedef ManyToManyMap<string, string> LinksMap;
LinksMap links;
links.insert("seg1", "pic1"); // seg1 -> (pic1) and pic1 -> (seg1)
links.insert("seg1", "pic2"); // seg1 -> (pic1, pic2) and pic2 -> (seg1)
links.insert("seg2", "pic1"); // seg2 -> (pic1) and pic1 -> (seg1, seg2)
....
links.removeKey("seg1"); // pic1 -> (seg2) and pic2 -> ()
这个数据结构有明显的缺陷,它不清理映射到空集。假设在最后一条语句中,pic2现在有一个空映射。您可以调整这个类,以确保从valueToKeys
或keyToValues
映射中删除空集映射,具体取决于是removeKey()
还是removeValue()
操作。
相关文章:
- 这个指针在c++中的用法
- 当C++中需要自动删除时,这是静态的正确用法吗?
- libstdc++ 文件系统中未初始化的用法?
- 复制和交换习惯用法与移动操作之间的交互
- 类作用域的类型别名"using":[何时]方法中的用法可以先于类型别名?
- 命名参数习惯用法和(抽象)基类
- 省略号在C++中的所有用法
- () 在 C++ 11 中的特殊而奇怪的用法?
- 构造函数的用法
- 模板类中自动的类用法不完整
- 这里的 = 运算符有什么用法?
- 什么模板用法在阶乘中更好
- 如果可变长度元素的constexpr用法得到<>
- 为什么 setjmp/longjmp 的这种用法是未定义的行为?
- 访问提升:shared_ptr 主范围外崩溃,断言失败:px != 0.指针的正确用法是什么?
- C++ 中函数中 Const 用法之间的差异
- equal_to模板类C++用法
- PCL 中的 GICP 用法
- 向量的正确用法<int>::size_type
- 重复键的bimmap用法