Access Key from Values and Value from Key



我的项目需要两个访问者。

  • 使用密钥访问值(简单)
  • 使用值访问密钥(有点棘手)

价值也将是唯一的在我的项目


请建议使用更好的容器以及如何使用?

我想使用STL或BOOST。

您要查找的是双向映射。

STL中没有,但您可以查看Boost.Bimap以了解另一个实现。

如果你想自己实现它,你可以简单地使用两个规则的单向映射。如果您使用指针,应该会有很少的内存开销和不错的性能。

这是我两天前在项目中使用的。

#include <boost/bimap.hpp>
class ClientManager
{
    typedef boost::bimap<
        boost::bimaps::set_of<int>,
        boost::bimaps::set_of<int>
    > ConnectedUsers; // User Id, Instance Id
    ConnectedUsers m_connectedUsers;
public:
    int getUserId(int instanceId);
    int getInstanceId(int userId);
};
int ClientManager::getInstanceId(int userId)
{
    auto it = m_connectedUsers.left.find(userId);
    return it->second;
}
int ClientManager::getUserId(int instanceId)
{
    auto it = m_connectedUsers.right.find(instanceId);
    return it->second;
}
...
// Insert
m_connectedUsers.insert(ConnectedUsers::value_type(id, instanceId));
// Erase
m_connectedUsers.left.erase(userId);

如果您想要双向访问,即key->value和value->key,那么您的设计可能不需要像map 这样的关联容器

尝试std::对的vector

附带说明一下,如果需要存储两个以上的值,可以使用std::tuple。

啊!!

最新更新