我的地图如下:
std::map< std::string ,int> mapobj;
mapobj["one"] = 1;
mapobj["two"] = 2;
mapobj["three"] =3 ;
输入为值时如何获取键
EX:
输入:1
输出:一个
注意:在我的情况下,值是唯一的
答案 0 :(得分:8)
一对一映射实际上很容易,最快的方法是维护两个 映射,每个方向一个。如果不是一对一的,它将变得更加复杂,因为您需要提供一种获取值或键的 collection 的方法,而不是单个方法。幸运的是,您只有一对一的要求。
其中一个映射就是您现在拥有的映射,另一个映射会将值映射到给定的键,两者都是:
std::map<std::string, int> forwardmapobj;
std::map<int, std::string> reversemapobj;
,它们将保留在某种bidimap
类中。
每当您插入bidimap
或从其中删除时,都必须在两个内部地图上执行相同的操作。
例如,这是一些伪代码。它会维护两个映射,并确保它们与您执行的更改键和值的任何操作保持同步:
class biDiMap:
map<string, int> forwardMap
map<int, string> reverseMap
void add(string key, int val):
if exists forwardMap[key]: throw exception 'duplicate key'
if exists reverseMap[val]: throw exception 'duplicate value'
forwardMapObj[key] = val
reverseMapObj[val] = key
void delKey(string key):
if not exists forwardMap[key]: throw exception 'no such key'
delete reverseMap[forwardMap[key]]
delete forwardMap[key]
void delVal(int val):
if not exists reverseMap[val]: throw exception 'no such value'
delete forwardMap[reverseMap[val]]
delete reverseMap[val]
int getValFor(string key): return forwardMap[key]
string getKeyFor(int val): return reverseMap[val]
很明显,您可以添加很多 other 东西,但这应该构成基础。无论如何,在将其转换为C ++类之前,您可能已经做了足够的 工作:-)
如果您不想想要推出自己的解决方案,那么Boost有一个很好的解决方案,您可以按原样使用。 Boost.Bimap
提供了一个完全模板化的双向地图,您应该可以使用最少的代码使用它,例如以下完整程序:
#include <iostream>
#include <string>
#include <boost/bimap.hpp>
using std::string;
using std::cout;
using std::exception;
using boost::bimap;
int main()
{
typedef bimap<string, int> SiMap;
typedef SiMap::value_type SiEntry;
SiMap bidi;
bidi.insert(SiEntry("ninety-nine", 99));
int i = 0;
for (string str: {"one", "two" , "three", "four", "five", "six"}) {
bidi.insert(SiEntry(str, ++i));
}
cout << "The number of entries is " << bidi.size() << "\n\n";
for (auto i = 1; i <= 7; i += 3) {
try {
cout << "Text for number " << i << " is " << bidi.right.at(i) << "\n";
} catch (exception &e) {
cout << "Got exception looking up number " << i << ": " << e.what() << "\n";
}
}
cout << "\n";
for (auto str: {"five", "ninety-nine", "zero"}) {
try {
cout << "Number for text '" << str << "' is " << bidi.left.at(str) << "\n";
} catch (exception &e) {
cout << "Got exception looking up text '" << str << "': " << e.what() << "\n";
}
}
cout << "\n";
return 0;
}
它在数字的文本形式和整数值之间创建双向映射,然后进行一些查找(在两个方向上)以表明其有效:
The number of entries is 7
Text for number 1 is one
Text for number 4 is four
Got exception looking up number 7: bimap<>: invalid key
Number for text 'five' is 5
Number for text 'ninety-nine' is 99
Got exception looking up text 'zero': bimap<>: invalid key
答案 1 :(得分:6)
我确实注意到它具有“ stdmap”标签,因此这可能不合适。但是Boost具有boost::bimap<>
,它可以让您做自己想做的事:它允许通过键或值进行查找。
答案 2 :(得分:2)
输入为值时如何获取键
首先,不能保证值是唯一的。我意识到您说的是独特的。尽管如此,从概念上讲,这还是解决问题时要记住的事情。
第二,std::map
未按值排序。因此,寻找值的最有效算法平均是O(N)
。
答案 3 :(得分:0)