簡體   English   中英

我試圖通過引用函數傳遞C ++映射並迭代它但我無法編譯代碼

[英]I'm trying to pass a C++ map by reference to a function and iterate through it but I cannot compile the code

我有一個相當簡單的問題。 我正在嘗試創建一個通過引用接受地圖並迭代地圖鍵的函數。

#include <map>
#include <string>
#include <sys/types.h>

using namespace std;

void update_fold_score_map(string subfold,
                           int32_t index,
                           int32_t subfold_score,
                           map<string, int32_t> &fold_scores){
  for(map<string, int32_t>::iterator i = fold_scores.begin();
      i != fold_scores.end();
      i ++){
    string current_substring;
    string fold;
    fold = (*i);
    current_substring = fold.substr(index, subfold.size());

    if (current_substring == subfold){
      if (fold_scores[fold] < subfold_score){
        fold_scores[fold] = subfold_score;
      }
      return;
    }
  }
}
int main(){
  return 0;
}

但是,我在“fold =(* i);”行收到錯誤 其中說明:

compilemap.cpp:16:15: error: no match for ‘operator=’ in ‘fold = i.std::_Rb_tree_iterator<_Tp>::operator* [with _Tp = std::pair<const std::basic_string<char>, int>, std::_Rb_tree_iterator<_Tp>::reference = std::pair<const std::basic_string<char>, int>&]()’
fold = (*i); // <- here

foldstd::string類型; (*i)map<string, int32_t>::value_type類型,恰好是std::pair<const string, int32_t> 。顯然,你不能稍后分配給前者。

你可能想要做的是,

fold = i->first; // which extracts "key" from the std::map<>::iterator

一張地圖它是一對的容器。 您可以使用 - >運算符訪問值部分:

 fold = i->second;

*我是一個std :: pair; 你應該寫

fold = i->first

獲取條目的關鍵。

嘗試以下代替fold = (*i)

fold = i->first;

暫無
暫無

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

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