我正在尝试使用循环来使用insert方法填充地图。我有一张地图,我试图使用这种方法填充:
void board:: insertToMap(Letter c, int num){
this->myRackMap.insert(pair<Letter, int>(c, num));
}
我在另一个方法中在这个循环中调用这个辅助方法:
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
当我尝试运行这个时,我得到一个非常长的错误消息,等待太长时间才能进入此状态。错误消息的结束行是这样的;但是:
“'const Letter'不是来自'const std :: multimap&lt; _Key,_Tp, _Compare,_Alloc&gt;' {return __x&lt; __y; }“
这让我相信错误与将我的struct Letter插入地图而不是原始数据类型有关。任何建议都会非常感激,因为我对c ++不太熟悉,感谢您提供的任何帮助!
编辑:这是Letter.h的样子
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();
};
和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
}
}
答案 0 :(得分:1)
使用std::map
订购的元素的key
键。因此,您需要为关键对象定义operator<
,在您的示例中为Letter
。或者在构建std::map
时提供比较器。
bool cmp(const Letter& lhs, const Letter &rhs) { ...define order... }
std::map<Letter, int, bool(*)(const Letter&, const Letter&)> myRackMap(cmp);
无论您决定使用哪种解决方案,都需要定义一种订购信件的方式,我认为xpos
,ypos
的组合定义了Letter
的唯一标识符。因此你可以这样写:
bool cmp(const Letter& lhs, const Letter &rhs) {
return lhs.xPos < rhs.xPos || (lhs.xPos == rhs.xPos && lhs.yPos < rhs.yPos);
}
或者如果您选择重载<
运算符:
bool Letter::operator<(const Letter &other) const {
return xPos < other.xPos || (xPos == other.xPos && yPos < other.yPos);
}