擦除嵌套的地图元素
Erase nested map elements
我有一张看起来像
的地图
typedef std::map<int, std::set<float>> innerMap;
typedef std::map<long, innerMap> outerMap;
我想做以下事情:
1. 我想擦除外层地图的一个键的内层地图元素。
2. 然后如果它包含 0 个内部地图元素,我想擦除外部地图键。
对于第一种情况,我将代码编写为:
outerMap mapA;
//assuming this map contain an element
//longx is key in outer element, intx is key of inner element
std::map<int, std::set<float>>::const_iterator innerIter = mapA[longx].begin();
while (innerIter != mapA[longx].end())
{
if (innerIter->first == intx)
{
if (innerIter->second.size() == 0)
{
mapA[longx].erase(innerIter++);
}
break;
}
++innerIter;
}
我用 C++ 编写了这段代码,但我想使用 C++11。我们可以在 C++11 中以更好的方式编写它吗?
对于第二种情况,我是否需要再次迭代外部映射并检查其值元素,或者我可以在现有代码中完成?
你目前在做什么(在 C++11 中):
auto& inner = mapA[longx];
const auto it = inner.find(intx);
if (it != inner.end() && it->second.size() == 0) {
inner.erase(it);
}
这段代码对我来说太复杂了。以下应该做同样的事情,不需要使用花哨的 C++11 功能:
outerMap mapA;
// Lookup iterator for element of outerMap.
outerMap::iterator const outerIter = mapA.find(longx);
// Lookup iterator for element of innerMap that should be checked.
innerMap::const_iterator const innerIter = outerIter->second.find(intx);
// Check if element of innerMap should be erased and erase it if yes.
if(innerIter != outerIter->second.end() && innerIter->second.size() == 0) {
outerIter->second.erase(innerIter);
}
// Erase element of outer map is inner map is now empty:
// This should do scenario 2
if(outerIter->second.size() == 0) {
mapA.erase(outerIter);
}
我有一张看起来像
的地图typedef std::map<int, std::set<float>> innerMap;
typedef std::map<long, innerMap> outerMap;
我想做以下事情:
1. 我想擦除外层地图的一个键的内层地图元素。
2. 然后如果它包含 0 个内部地图元素,我想擦除外部地图键。
对于第一种情况,我将代码编写为:
outerMap mapA;
//assuming this map contain an element
//longx is key in outer element, intx is key of inner element
std::map<int, std::set<float>>::const_iterator innerIter = mapA[longx].begin();
while (innerIter != mapA[longx].end())
{
if (innerIter->first == intx)
{
if (innerIter->second.size() == 0)
{
mapA[longx].erase(innerIter++);
}
break;
}
++innerIter;
}
我用 C++ 编写了这段代码,但我想使用 C++11。我们可以在 C++11 中以更好的方式编写它吗?
对于第二种情况,我是否需要再次迭代外部映射并检查其值元素,或者我可以在现有代码中完成?
你目前在做什么(在 C++11 中):
auto& inner = mapA[longx];
const auto it = inner.find(intx);
if (it != inner.end() && it->second.size() == 0) {
inner.erase(it);
}
这段代码对我来说太复杂了。以下应该做同样的事情,不需要使用花哨的 C++11 功能:
outerMap mapA;
// Lookup iterator for element of outerMap.
outerMap::iterator const outerIter = mapA.find(longx);
// Lookup iterator for element of innerMap that should be checked.
innerMap::const_iterator const innerIter = outerIter->second.find(intx);
// Check if element of innerMap should be erased and erase it if yes.
if(innerIter != outerIter->second.end() && innerIter->second.size() == 0) {
outerIter->second.erase(innerIter);
}
// Erase element of outer map is inner map is now empty:
// This should do scenario 2
if(outerIter->second.size() == 0) {
mapA.erase(outerIter);
}