【问题标题】:Why doesn't map insert?为什么地图不插入?
【发布时间】:2019-12-13 16:35:04
【问题描述】:

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

【问题讨论】:

  • 修改 m_LapMap.end( ) 的内容看起来很奇怪。
  • 结束迭代器在最后一个对象之后。当itLap == m_LapMap.end( ) itLap 指向一个有效对象时?
  • 休息一下,想想你想要达到的目标,不是这样。
  • 是的。我明白为什么它不工作了。尝试将新的 UapMap 插入 LapMap。需要创建UapMap,然后插入,而不是在map.end

标签: c++ dictionary insert iterator


【解决方案1】:

itLap == m_LapMap.end( ) 时,您使用的是itLap-&gt;second

std::map::end() 返回一个占位符元素并尝试访问它会调用未定义的行为

UpdateLapMap 没有插入UapMap,因为没有插入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获取迭代器。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多