c++ - 为什么不插入地图?
问题描述
为什么找不到圈时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 %d\n", 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->second
when itLap == m_LapMap.end( )
。
std::map::end()
返回一个占位符元素并尝试访问它会调用未定义的行为。
UpdateLapMap
不插入 aUapMap
因为没有代码可以插入 a UapMap
,所以你应该添加它。
例如:
if ( itLap == m_LapMap.end( ) )
{
printf( "not found - insert new lap %d\n", 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
.
推荐阅读
- php - 事务内卷曲
- javascript - 自定义 Highcharts 工具提示
- java - 正则表达式验证必须包含至少两个非字母字符的八个或更多字符字符串
- javascript - Get the nearby objects of array item
- java - 在类内部创建对象但在外部方法与在方法内部创建对象有什么区别
- airflow - 如何防止追赶 DAG?
- javascript - 除了用连字符分隔的拆分之外,查找字符串大小的方法?
- java - java - 如何在java中使用数组if else和foreach创建方法
- angular - when using [(ngModel)] directive, what is the event expression called to detect change?
- tensorflow - Jetson TX2 tensorflow per_process_gpu_memory_fraction variable cannot set to 1.0