user1005909
user1005909

Reputation: 1975

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

I have a fairly simple problem. I'm trying to make a function that accepts a map by reference and iterates through the keys of the map.

#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;
}

But, I'm getting an error at the line "fold = (*i);" which states:

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>&]()’

Upvotes: 3

Views: 2292

Answers (4)

hatboyzero
hatboyzero

Reputation: 1937

Try the following instead of fold = (*i)

fold = i->first;

Upvotes: 2

Seth Carnegie
Seth Carnegie

Reputation: 75130

*i is an std::pair; you should write

fold = i->first

To get the key of the entry.

Upvotes: 2

CapelliC
CapelliC

Reputation: 60014

a map it's a container of pair. you can access the value part using the -> operator:

 fold = i->second;

Upvotes: 2

Alexander Poluektov
Alexander Poluektov

Reputation: 8053

fold = (*i); // <- here

fold is of std::string type; whereas (*i) is of map<string, int32_t>::value_type type, which happens to be std::pair<const string, int32_t>.Obviously, you cannot assign later to the former.

What you probably want to do, is to

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

Upvotes: 5

Related Questions