我试图通过引用函数传递C++映射并迭代它但我无法编译代码

use*_*909 3 c++

我有一个相当简单的问题.我正在尝试创建一个通过引用接受地图并迭代地图键的函数.

#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;
}
Run Code Online (Sandbox Code Playgroud)

但是,我在"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>&]()’
Run Code Online (Sandbox Code Playgroud)

Ale*_*tov 5

fold = (*i); // <- here
Run Code Online (Sandbox Code Playgroud)

fold属于std::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
Run Code Online (Sandbox Code Playgroud)

  • `i-> first`对我来说似乎更常规(以及将`i`重命名为`it`BTW). (4认同)