我正在回答初学者C ++书中的一个问题。我在std::map
上做了一节。问题是创建一个带有排序谓词的映射,映射需要是一个自定义结构(wordProperty)作为键,定义(字符串)作为值。
我收到了错误;
错误1错误C2664:'bool fPredicate :: operator()(const std :: string&,const std :: string&)const':无法将参数1从'const wordProperty'转换为'const std: :string&' c:\ program files(x86)\ microsoft visual studio 12.0 \ vc \ include \ xutility 521 1 c ++ test1
指第52行,这是代码的一部分:
bool operator < (const wordProperty& item) const
{
return(this->strWord < item.strWord);
}
程序允许用户输入单词,输入单词是否来自拉丁语并输入定义,然后在每次输入后打印字典。
#include "stdafx.h"
#include <iostream>
#include <Windows.h>
#include <map>
#include <algorithm>
#include <string>
using namespace std;
template <typename T>
void DisplayContents(const T& Input)
{
for (auto iElement = Input.cbegin(); iElement != Input.cend(); ++iElement)
cout << iElement->first << " -> " << iElement->second << endl;
cout << endl;
}
struct fPredicate
{
bool operator()(const string& str1, const string& str2) const
{
string str1temp(str1), str2temp(str2);
transform(str1.begin(), str1.end(), str1temp.begin(), tolower);
transform(str2.begin(), str2.end(), str2temp.begin(), tolower);
return(str1temp < str2temp);
}
};
struct wordProperty
{
string strWord;
bool bIsFromLatin;
wordProperty(const string& strWord, const bool & bLatin)
{
this->strWord = strWord;
bIsFromLatin = bLatin;
}
bool operator == (const wordProperty& item) const
{
return(this->strWord == item.strWord);
}
bool operator < (const wordProperty& item) const
{
return(this->strWord < item.strWord);
}
operator const char*() const
{
string temp = this->strWord;
if (this->bIsFromLatin)
{
temp += " is from Latin.";
}
else
temp += " is not from Latin.";
return temp.c_str();
}
};
int main()
{
map<wordProperty, string, fPredicate> mapWordDefinition;
while (true)
{
cout << "Add a new word: ";
string newWord;
cin >> newWord;
cout << "Is this word from Latin (Y/N)? ";
string YN;
bool newLatin;
if ((YN == "Y") || (YN == "YES") || (YN == "y") || (YN == "yes") || (YN == "Yes"))
newLatin = true;
else
newLatin = false;
cout << "What is the definition of this word? ";
string definition;
cin >> definition;
mapWordDefinition.insert(make_pair(wordProperty(newWord, newLatin), definition));
cout << endl;
DisplayContents(mapWordDefinition);
cout << endl;
}
}
答案 0 :(得分:0)
谓词需要使用地图的键类型。
更改
bool operator()(const string& str1, const string& str2) const;
到
bool operator()(const wordProperty& wp1, const wordProperty& wp2) const;
在该功能的实现中,您可以提取对象strWord
和wp1
的{{1}}成员,并遵循您的逻辑。