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

前端 未结 5 935
庸人自扰
庸人自扰 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: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 
    using map2d = std::map, V>;
    
    int main() {
        map2d 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;
        }
    }
    

提交回复
热议问题