'How to insert struct into stl::map C++
I am trying to use a loop to populate a map using the insert method. I have a map that I am trying to populate using this method:
void board:: insertToMap(Letter c, int num){
this->myRackMap.insert(pair<Letter, int>(c, num));
}
and I call this helper method in this loop within another method:
void board:: getRackAsMap(){
for (int i = 0; i < this->getMyRack().size(); ++i){
insertToMap(this->getMyRack().at(i), this->getMyRack().at(i).readScore());
}
}
//myRackMap is a map<Letter, int>
//myRack is a vector<Letter>
vector<Letter>& board::getMyRack(){
return this->myRack;
}
//readScore returns an Int value based on the char value of the current Letter
When I try to run this I get a ridiculously long error message, waaay too long to put into this. The ending line of the error message is this; however:
"‘const Letter’ is not derived from ‘const std::multimap<_Key, _Tp, _Compare, _Alloc>’ { return __x < __y; }"
which led me to believe that the error is related to inserting my struct Letter into the map instead of a primitive data type. Any advice would be greatly appreciated as I am not too familiar with c++, thank you for any help you can provide!
EDIT: here is what Letter.h looks like
struct Letter{
private:
char theLetter;
int xPos;
int yPos;
public:
Letter();
Letter(char c);
Letter(int x, int y, char c);
void setPos(int x, int y);
void setLetter(char c);
int getXPos();
int getYPos();
char getTheLetter();
int readScore();
};
and letter.cpp
Letter:: Letter(){
this->xPos = -1;
this->yPos = -1;
this->theLetter = '?';
}
Letter:: Letter(char c){
this->xPos = -1;
this->yPos = -1;
this->theLetter = c;
}
Letter:: Letter(int x, int y, char c){
this->xPos = x;
this->yPos = y;
this->theLetter = c;
}
int Letter:: getXPos(){
return this->xPos;
}
int Letter:: getYPos(){
return this->yPos;
}
char Letter:: getTheLetter(){
return this->theLetter;
}
void Letter:: setPos(int x, int y){
this->xPos = x;
this->yPos = y;
}
void Letter:: setLetter(char c){
this->theLetter = c;
}
int Letter:: readScore(){
switch (this->getTheLetter()){
case 'A':
return 1;
break;
case 'B':
return 3;
break;
//etc etc, returns int based on char of Letter
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
