-3

my program wont compile because it did not found match for the operand. It accesses the map in struct Student, I am not sure if this is the exact way to access map.

my program wont compile because it did not found match for the operand. It accesses the map in struct Student, I am not sure if this is the exact way to access map.

#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <string>
#include <map>
#include <list>


using namespace std;

struct Student {
    string id;
    map<string, int> scores;
};

istream& operator >>(istream &is, Sudent& g) {

    auto it = g.scores.begin();
    is >> g.id >> it->first >> it.second;
    return is;
}

On >> it->first I get this error:

Error: no operator ">>" matches these operands
    operand types are: std::basic_istream<char, std::char_traits<char>> >> const std::string
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
XDProgrammer
  • 853
  • 2
  • 14
  • 31

2 Answers2

6

You may use temporary variables

std::string tempStr;
int tempInt;
is >> g.id >> tempStr >> tempInt;
scores.insert( std::pair<std::string,int>(tempStr , tempInt));
Steephen
  • 14,645
  • 7
  • 40
  • 47
  • 2
    Right solution, but needs an explanation of why what the OP did was wrong. Solution without explanation leads to cargo cult behaviour. – user4581301 Jun 26 '15 at 19:51
4

The error is due to the fact that it->first is of type const string, not string.

Apart from this, you need to find a way to read that map by reading an (unknown) number of string(s) and the corresponding int. How to do that depends on how they are stored in the file.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
marom
  • 5,064
  • 10
  • 14
  • Why would `it->first` be `const`, though? `g` is not `const`, and `g.scores` is not `const`, so why is the `const` version of `g.scores.begin()` being called? Is it a side effect of using `auto` to accept a return value from an overloaded method? Changing `auto` to `map::iterator` should fix the error. – Remy Lebeau Jun 26 '15 at 20:08
  • it->first is const because in a map the key is immutable. Allow to change it->first would mean change the position/order of the object inside the container. That's equivalent to an deletion/insertion – marom Jun 26 '15 at 20:11
  • OK, thanks for the info. – Remy Lebeau Jun 26 '15 at 20:18