重复键的bimmap用法

bimap usage for repeated keys

本文关键字:bimmap 用法      更新时间:2023-10-16

根据这个问题中使用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现在有一个空映射。您可以调整这个类,以确保从valueToKeyskeyToValues映射中删除空集映射,具体取决于是removeKey()还是removeValue()操作。