Error "no match operator []" when entering data in a map inside an object

1

I'm trying to save data on a map inside an object and I get this error in var [name] = val and in var [name]:

  

no match operator []

header

#include <string>
#include <map>
using namespace std;

class Calculator{
public: 
    void addVal(string name, int val);
    int getVal(string name);
private:
    int memory;
    map <string,int>* var;
};

cpp

#include "Calculator.h"
#include <string>
#include <map>
using namespace std;

Calculator::Calculator():
memory(0), var(new map<string, int>)
{}
void Calculator::addVal(string name, int val){

    var[name]=val;

}

int Calculator::getVal(string name){
    return var[name];

}

What am I doing wrong?

    
asked by Diego Fernando Martinez 16.11.2016 в 07:57
source

2 answers

2
class Calculator{
private:
    map <string,int>* var;
//                  ^
};

Look at that asterisk ... thanks to him, var is a pointer. If the access to the map is done through a pointer you should write something such that:

void Calculator::addVal(string name, int val){
    (*var)[name]=val;
}

Although you could also do the following:

void Calculator::addVal(string name, int val){
    var->operator[](name)=val;
}

Even so, everything indicates that the error in your case is the use of the asterisk. Delete it and then you can access the map methods without problems.

As a final note, try not to use using namespace in the header files. In bigger programs it can give you problems.

Your corrected code would look like this:

class Calculator{
public: 
    void addVal(string name, int val);
    int getVal(string name);
private:
    int memory;
    map <string,int> var;
};

Calculator::Calculator()
  : memory(0)
{ }
void Calculator::addVal(string name, int val){
  var[name]=val;
}

int Calculator::getVal(string name){
  return var[name];
}
    
answered by 16.11.2016 / 09:03
source
1

If you compile it, it gives you the errors:

  • The member functions addVal and getVal do not have the return in the declaration but if they have it in the definition, so the compiler can not identify them.
  • getVal is declared with the parameters (string, name) and defined with the parameter (string name) .
  • You define the constructor of Calculator but you do not declare it.
  • var is a pointer not an object, to use it you should first de-reference and then use: (*var)[name] = val and return (*var)[name] .

By the way, you do not delete var in the destructor.

Have you tried to compile or understand the errors? They seem pretty self-explanatory.

    
answered by 16.11.2016 в 09:05