Reverse map lookup

前端 未结 8 812
囚心锁ツ
囚心锁ツ 2020-11-30 05:37

I have a 1 to 1 map. What\'s the best way to find keys from values,

i.e.

For examples if the map is this

KEY VALUE

a    1
b    2
c          


        
8条回答
  •  -上瘾入骨i
    2020-11-30 06:03

    Unless the map is huge, or you have some other way of knowing that linear search is too slow, I'd start with linear search:

    #include 
    using std::cout;
    
    #include 
    using std::map;
    
    #include 
    using std::find_if;
    
    #include 
    using boost::assign::map_list_of;
    
    typedef map Map;
    typedef Map::key_type Key;
    typedef Map::value_type Pair;
    typedef Map::mapped_type Value;
    
    
    struct finder {
        const Value v;
        finder(const Value& v) : v(v) {}
        bool operator()(const Pair& p) {
            return p.second == v;
        }
    };
    
    Map m = map_list_of('a', 1)('b', 2)('c', 3)('d', 4)('e', 5);
    
    int main() {
        Pair v = *find_if(m.begin(), m.end(), finder(3));
        cout << v.second << "->" << v.first << "\n";
    }
    

提交回复
热议问题