2017-02-10 104 views
1

我使用polinoms並將它們作爲度和係數保存在std :: map中。下面的代碼片段:使用std :: map時只讀成員的錯誤遞減:: map

std::map<int,int> pol; 

地圖充滿了數據,然後我就開始對其進行處理。

for(std::map<int,int>::iterator it = pol.begin(); it != pol.end(); it++) { 
       if(it->first != 0) { 
         it->second *= it->first; 
         it->first--; 
       } 
       else { 
         it->first = 0; 
         it->second = 0; 
       } 
} 

而且從它 - >序曲一開始,並進一步我得到非常大的量與像error: decrement of read-only member ‘std::pair<const int, int>::first’ it->first--; ^~ error: assignment of read-only member ‘std::pair<const int, int>::first’ it->first = it->first - 1; 錯誤輸出爲什麼只讀?我該如何解決它?

$ g++ --version 
g++ (Debian 6.3.0-5) 6.3.0 20170124 
+0

[強制鍵類型的std :: map不是const的可能的重複](http://stackoverflow.com/questions/6773734/force-key-type-of-a-stdmap-not-to- be-const) – nwp

回答

4

它是隻讀的,因爲如果你被允許自由修改地圖的關鍵,你將違反數據結構中的地圖應用(通常爲紅黑樹)的不變。

您需要刪除該元素並將其添加回減值。這確保節點將在樹中的正確位置。

+0

有沒有辦法在原地修改數值(不是鍵)? – synchronizer

+3

@synchronizer不存在;如果你需要這樣做,這意味着'map'不是你的應用程序的正確數據結構 –

+0

那麼你怎麼創建一個簡單的詞頻詞典。我很確定我已經完成了這項工作......我會檢查。編輯:反例? http://stackoverflow.com/questions/4527686/how-to-update-stdmap-after-using-the-find-method – synchronizer