簡體   English   中英

Unordered_map(C ++)中的“錯誤:分配只讀位置”

[英]“error: assignment of read-only location” in unordered_map (C++)

我有一個笨拙的哈希表(特別是unordered_map),其中包含int鍵和vector< vector< int >>數據。 我定期需要更新此int的二維向量中的元素。 沒有內在的原因我不應該對吧? 我改用了一種較新的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.內部版本5465)中沒有出現。 如果我沒有緊迫的期限,我將嘗試更仔細地分析錯誤!

你確定真的有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 );
( piItr -> second )[ thisStep ].at( d )

at()將迭代器返回到內部向量中,而不訪問該值。 你想要的是

 *(( piItr -> second )[ thisStep ].at( d ))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM