Reverse map lookup

前端 未结 8 813
囚心锁ツ
囚心锁ツ 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条回答
  •  粉色の甜心
    2020-11-30 06:06

    Given a std::map from keys to values, the following function will return a reverse lookup table, a std::map from values to keys.

        /// Given a map from keys to values, creates a new map from values to keys 
        template
        static map reverse_map(const map& m) {
            map r;
            for (const auto& kv : m)
                r[kv.second] = kv.first;
            return r;
        }
    

提交回复
热议问题