为什么不插入地图?
Why doesn't map insert?
为什么 UpdateLapMap 在找不到圈数时不插入 UapMap?
typedef std::map<int, int> UapMap; // map of uap counters
typedef std::map<int, UapMap> LapMap; // map of UapMaps
LapMap m_LapMap;
void MyClass::UpdateLapMap( int lap, int * uaps, size_t n_uaps )
{
std::map<int, UapMap>::iterator itLap = m_LapMap.find( lap );
if ( itLap == m_LapMap.end( ) )
{
printf( "not found - insert new lap %dn", lap );
for ( size_t i = 0; i < n_uaps; i++ ) itLap->second[ uaps[ i ] ] = 1; // initial count
}
else
{
/// insert and/or increment uap counters
}
}
您在itLap == m_LapMap.end( )
时使用itLap->second
。
std::map::end()
返回一个占位符元素,尝试访问它会调用未定义的行为。
UpdateLapMap
不会插入UapMap
,因为没有代码可以插入UapMap
,所以你应该添加它。
例如:
if ( itLap == m_LapMap.end( ) )
{
printf( "not found - insert new lap %dn", lap );
itLap = m_LapMap.insert( LapMap::value_type( lap, UapMap() ) ).first; // add this line
for ( size_t i = 0; i < n_uaps; i++ ) itLap->second[ uaps[ i ] ] = 1; // initial count
}
这里使用std::map::insert()
返回一对指向插入元素的迭代器和一个布尔值,指示插入是否已完成或键是否已存在,因此迭代器是通过.first
获取的。
相关文章:
- 将一对插入地图并增加计数?
- 当我将其插入无序地图时,矢量的容量为 0
- 如何将元素插入到标准::地图的共享指针中?
- 无法插入到标准地图
- 为什么不插入地图?
- 为什么emplace_hint比插入地图慢?
- 地图插入(const_iterator提示,值)用法
- 无法将智能指针插入地图
- 插入到地图中,以对作为键并列出作为值
- 地图插入不明确
- VS 2017 错误 C2664 地图插入尝试
- 为什么通用参考概念不适用于函数指针的地图插入
- 地图插入将替换以前输入的值
- 地图插入密钥,但没有值
- 如何在CPU和内存中优化C 中的重型地图插入
- 我如何将MPL地图插入
- 地图::插入正在中断
- 我不明白地图插入上的此错误
- C++ 多重地图插入功能
- 地图插入返回错误答案的地图