检查地图中地图中是否存在元素

时间:2013-10-30 16:57:40

标签: c++ stl

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

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

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

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

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

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

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

5 个答案:

答案 0 :(得分:5)

您可以将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)

答案 1 :(得分:1)

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

答案 2 :(得分:1)

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

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

答案 3 :(得分:1)

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

答案 4 :(得分:0)

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