首页 > 解决方案 > 为什么不插入地图?

问题描述

为什么找不到圈时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
   }
}

标签: c++dictionaryinsertiterator

解决方案


您正在使用itLap->secondwhen 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.


推荐阅读