Checking whether an element exist or not in the map within map

前端 未结 5 899
庸人自扰
庸人自扰 2021-01-24 22:07

I have a map of the form map > :

For Example: I am storing the intensity value at 2-D co-ordinate(x,y) i

相关标签:
5条回答
  • 2021-01-24 22:26

    This is bit ugly but should work too : (using C++11)

    std::map<int, std::map<int, double> > intensityValue;
    int x,y;
    auto it = std::find_if(intensityValue.begin(),
                        intensityValue.end(),
                        [x,y](const std::pair<int, std::map<int, double>>& p){
                          return p.first==x && 
                                 p.second.find(y) !=p.second.end();
                        }
                        );
    
      if(it != intensityValue.end())
      {
          //Got it !
      } 
    
    0 讨论(0)
  • 2021-01-24 22:31

    You can use std::map::find together with short-circuit evaluation:

    bool foundXY = instensityValue.find(x) != intensityValue.end() &&
                   intensityValue[x].find(y) != intensityValue[x].end();
    

    or std::map::count:

    bool foundXY = instensityValue.count(x) && intensityValue[x].count(y)
    
    0 讨论(0)
  • 2021-01-24 22:36

    Write a short function for it to ensure the minimum number of map finding is called.

    bool hasIntensity(int x, int y)
    {
        map<int, map<int, double> >::const_iterator i = intensityValue.find(x);
        if (i == intensityValue.end()) return false;
        map<int, double>::const_iterator j = i->second.find(y);
        return j != (i->second.end());
    }
    

    If you want to get the actual value when the element is found, just utilize j->second.

    0 讨论(0)
  • 2021-01-24 22:41

    Use std::map::find

    auto outerIt = intensityValue.find(x);
    if (outerIt != intensityValue.end()) {
        auto innerIt = outerIt->find(y);
        if (innerIt != outerIt->end()) {
            // Do something with the found value
            return;
        }
    }
    // Didn't return, so it wasn't found
    

    That said, in my experience, using a single map of pairs for this kind of thing is more efficient and easier to use than a nested map. It fits better into standard algorithms and doesn't involve nearly as much tree navigation.

    template <typename T, typename U, typename V>
    using map2d = std::map<std::pair<T, U>, V>;
    
    int main() {
        map2d<int, int, double> myMap {
            {{3, 4}, 808.14f},
            {{1, 2}, 333.33f}
        };
        auto it = myMap.find({3, 4});
        if (it != myMap.end()) {
            std::cout << it->second << std::endl;
        }
    }
    
    0 讨论(0)
  • 2021-01-24 22:42

    You can use std::map::find and check if the element exists before accessing it. You can read the usage/documentation here: http://en.cppreference.com/w/cpp/container/map/find

    0 讨论(0)
提交回复
热议问题