为什么不插入地图?

Why doesn't map insert?

本文关键字:地图 插入 为什么不      更新时间:2023-10-16

为什么 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获取的。