当请求的键丢失时,有没有办法从矢量映射 return std::vector ref ?

Is there a way to return std::vector ref from a map of vectors when the requested key is missing?

快速说明:我目前无法访问此项目的 C++11,因此虽然我有兴趣听到使用它的任何答案,但我无法使用任何特定于 C++11 的内容。


我有一个管理对象集合的 class。此数据存储在向量映射中,以枚举 "object type" 作为键:

std::map<MyEnum, std::vector<MyObject *> > m_objectMap;

枚举值是对象的一部分,因此集合最初是这样填充的:

void MyCollection::AddObject(MyObject *object)
{
    m_objectMap[object->GetType()].push_back(object);
}

我现在想要做的是拥有一个函数,该函数采用枚举值和 returns 对相应向量的 const 引用。我可以这样做:

const std::vector<MyObject *> &MyCollection::GetObjectsForType(MyEnum eType)
{
    return m_objectMap[eType];
}

唯一的问题是,使用 std::map::operator[] 是非 const,因为如果集合中不存在请求的枚举类型,它会添加一对,这意味着此函数不能是 const。或者,如果我先检查地图以查看它是否包含密钥,如果密钥不存在,我不知道 return 怎么办,因为它必须是对 的 const 引用东西.

因此,我正在寻找有关设计此集合的更好方法的建议(或 return 空 const 向量引用的方法)。主要目标围绕易用性:

谢谢!

我会这样做:

const std::vector<MyObject *> &GetObjectsForType(MyEnum eType)
{
    static const std::vector<MyObject *> empty_vec;
    auto it = m_objectMap.find(eType);
    return it != m_objectMap.end() ? it->second : empty_vec;
}

关于整体设计,std::multimap<MyEnum, MyObject *>是我的选择。那么 GetObjectsForType() 可能是:

std::pair<iterator, iterator> GetObjectsForType(MyEnum eType)
{
    return m_objectMap.equal_range(eType);
}

我也会考虑使用 boost::unique_ptr<MyObject> 而不是原始指针。