检查元素是否存在于映射中的映射中

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

本文关键字:映射 元素 是否 存在 于映射 检查      更新时间:2023-10-16

我有一张map<key1, map<key2, value> >形式的地图

例如:我将强度值存储在以下地图中的二维坐标(x,y)中:

map<int, map<int, double> > intensityValue;

现在,我想检查坐标 (x,y) 处的强度值是否存在在此地图中。我知道的一种方法是检查:

if(intensityvalue[x][y] >=0)

在这种情况下,如果 Map 中不存在intensityValue[x][y]那么在检查后它会自动在我不想要的地图中插入intensityValue[x][y]

请提出一种有效的方法,以便我可以检查intensityValue[x][y]是否已经存在于地图中,而无需将其插入地图中。

您可以将std::map::find与短路评估一起使用:

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

std::map::count

bool foundXY = instensityValue.count(x) && intensityValue[x].count(y)

您可以使用std::map::find并在访问元素之前检查该元素是否存在。您可以在此处阅读用法/文档:http://en.cppreference.com/w/cpp/container/map/find

为它编写一个简短的函数,以确保调用的地图查找次数最少。

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());
}

如果要在找到元素时获取实际值,只需使用 j->second

使用 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

也就是说,根据我的经验,使用单个对映射进行这种事情比嵌套映射更有效,更易于使用。它更适合标准算法,并且不涉及那么多的树导航。

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;
    }
}

这有点丑,但也应该有效:(使用 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 !
  }