检查元素是否存在于映射中的映射中
Checking whether an element exist or not in the map within map
我有一张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 !
}
相关文章:
- 如何从存储在std::映射中的std::集中删除元素
- 从嵌套在std::映射中的std::列表中删除元素的最佳方式
- 删除映射和分割错误中的一个过去结束元素
- 为什么在 std::map 上移动无法将元素从一个映射移动到另一个映射
- 访问映射向量的映射元素(c++)
- 为什么 unordered_map::equal_range upper_bound 如果键小于第一个映射元素,则返回
- 根据类成员对同一密钥的多映射元素进行排序
- C++查找并擦除多映射元素
- C++ for_each循环找不到指向映射元素
- 创建映射元素时,请避免使用值副本
- 从常量迭代器到映射向量,获取映射向量中映射元素的键和值
- c++中如何更改映射元素的值
- 传递对映射元素的引用作为参数
- 如果没有找到映射元素将返回什么
- 不能访问指针-向量映射元素
- 存储内部排序映射元素的最快方式
- 无序多映射元素插入
- 哈希映射元素的值未正确打印
- 修改所有映射元素的键
- 复制映射元素的正确方法