Reverse map lookup

前端 未结 8 808
囚心锁ツ
囚心锁ツ 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:16

    A variation on @Robᵩ's answer above that uses a lambda:

    map<char, int> m = {{'a', 1}, {'b', 2}, {'c', 3}, {'d', 4}, {'e', 5}};
    
    int findVal = 3;
    auto it = find_if(m.begin(), m.end(), [findVal](const Pair & p) {
        return p.second == findVal;
    });
    if (it == m.end()) {
        /*value not found*/
        cout << "*value not found*";
    }
    else {
        Pair v = *it;
        cout << v.second << "->" << v.first << "\n";
    }
    

    (thanks to @Nawaz for his/her contribution here: https://stackoverflow.com/a/19828596/1650814)

    0 讨论(0)
  • 2020-11-30 06:17

    I know this is a really old question but this codeproject article (http://www.codeproject.com/Articles/3016/An-STL-like-bidirectional-map) is a pretty good example of a bidirectional map.

    This is an example program that shows how easy it is:

     #pragma warning(disable:4503)
    
        #include "bimap.h"
        #include <iostream>
        #include <string>
    
        using codeproject::bimap;
    
        int main(void)
        {
          bimap<int,std::string> bm;
    
          bm[1]="Monday";
          bm[2]="Tuesday";
          bm[3]="Wednesday";
          bm[4]="Thursday";
          bm[5]="Friday";
          bm[6]="Saturday";
          bm[7]="Sunday";
    
          std::cout<<"Thursday occupies place #"<<bm["Thursday"]<<
                     " in the week (european style)"<<std::endl;
          return 0;
        }
    
    0 讨论(0)
提交回复
热议问题