2

我有一个带有int键和vector< vector< int >>数据的尴尬哈希表(特别是 unordered_map)。我需要定期更新这个二维整数向量中的元素。没有内在的原因我不应该这样做,对吧?我切换到的较新的 g++ 编译器抱怨在下面指定的行上分配了只读位置。

typedef std::tr1::unordered_map< int, vector< vector< int > > > pimap;

vector< Strain * > liveStrains;
pimap phenotypeIs;
int NUM_DEMES = 3;

...
vector< Strain * >::const_iterator lsItr;
for ( lsItr = liveStrains.begin(); lsItr != liveStrains.end(); ++lsItr ) {
 int thisP = (*lsItr)->getPhenotype();
 pimap::iterator piItr = phenotypeIs.begin();
 piItr = phenotypeIs.find( thisP );
 if ( piItr != phenotypeIs.end() ) {
   for ( int d = 0; d < NUM_DEMES; d++ ) {
      ( piItr -> second )[ thisStep ].at( d ) = (*lsItr)->getI( d );  // error here
   }
 }
}

我是 C++ 新手,所以没有什么太明显的。感谢您的任何帮助。


按照蒂姆的建议

我已将上面代码的相关部分替换为以下内容:

  pimap::iterator piItr = phenotypeIs.find( thisP );
  if ( piItr != phenotypeIs.end() ) {
    for ( int d = 0; d < NUM_DEMES; d++ ) {
      vector< vector< int > > & thisVec2 = piItr->second;
      vector<int> & thisVec = thisVec2.at( thisStep );
      int & ii = thisVec.at( d );
      ii = (*lsItr)->getI( d );
      // ( piItr -> second )[ thisStep ].at( d ) = (*lsItr)->getI( d ); // error was here
    }

此代码编译没有错误,并且似乎运行良好。像蒂姆一样,我仍然不太明白为什么修复有效。该错误以前出现在 gcc 版本 4.1.2 20080704 (Red Hat 4.1.2-44) 但不是 gcc 版本 4.0.1 (Apple Inc. build 5465)。当我没有紧迫的最后期限时,我会尝试更仔细地剖析错误!

4

2 回答 2

1

您确定thisStep + 1每个第一级向量中确实有元素,每个NUM_DEMES第二级向量中都有元素吗?

如果我没看错,你实际上并没有分配给地图迭代器,所以我怀疑错误出在向量访问中。

将最后一条语句分解为多个语句可能会有所帮助,以便每个语句只执行一件事以缩小问题所在。例如,

Strain* strain = *lsItr;
vector<vector<int> >& vv = piItr->second;
vector<int>& v = vv[thisStep];
int& i = v.at(d);     // <-- My bet is that the error occurs here or the prev. line
i = strain->getI( d );

顺便说一句,piItr = phenotypeIs.begin();这里没有效果,它可能很简单:

pimap::iterator piItr = phenotypeIs.find( thisP );
于 2009-11-19T00:28:18.887 回答
-1
( piItr -> second )[ thisStep ].at( d )

at() returns an iterator into the inner vector, not access to the value. What you want is

 *(( piItr -> second )[ thisStep ].at( d ))
于 2009-11-19T01:11:48.060 回答