【发布时间】:2015-04-09 09:47:46
【问题描述】:
我的项目需要两个访问器。
- 使用键访问值(简单)
- 使用值访问密钥(有点棘手)
价值在我的项目中也是独一无二的
请建议使用更好的容器以及如何使用?
我想使用 STL 或 BOOST。
【问题讨论】:
我的项目需要两个访问器。
价值在我的项目中也是独一无二的
请建议使用更好的容器以及如何使用?
我想使用 STL 或 BOOST。
【问题讨论】:
您要查找的内容称为bidirectional map。
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 这样的关联容器
尝试vector 或std::pair。
附带说明,如果您需要存储两个以上的值,可以使用std::tuple。
HTH!!
【讨论】: