我需要一种通过传入值可能具有的任何键来访问值的方法。 例如,可以通过其 ip 地址或名称访问的播放器对象?
举例说明。
Player1 有 ["a", "1.2.3.4"]
Player2 有 ["b", "3.4.5.6"]
Player3 有 ["c", "2.2.9.3"]
因此,要访问 Player2,我可以使用 players["b"]
或 players["3.4.5.6"]
我应该为此迭代一个 vector 吗?但我计划有大约 100 个元素,那么树状容器会比数组列表更好吗?
你能为此使用 std::multimap
吗?
或者甚至在 std::map
中?
最佳答案
确保 ip
和 name
是唯一的。
map<string, Player> byNameMap;
map<string, Player> byIpMap;
void add(Player p) {
byNameMap[p.name] = p;
byIpMap[p.ip] = p;
}
void remove(Player p) {
byNameMap.erase(byNameMap.find(p.name));
byIpMap.erase(byIpMap.find(p.ip));
}
// assuming you are sure player with such name exists
void removeByName(string name) {
remove(byNameMap[name]);
}
// assuming you are sure player with such ip exists
void removeByIp(string ip) {
remove(byIpMap[ip]);
}
关于c++ - 使用 C++ 中的多个键之一访问相同的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36332013/