尝试创建具有自定义顺序的 std::map

Trying to create a std::map with a custom ordering

我正在回答初学者 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;

}
}

谓词需要与映射的键类型一起使用。

改变

bool operator()(const string& str1, const string& str2) const;

bool operator()(const wordProperty& wp1, const wordProperty& wp2) const;

在函数的实现中,您可以提取对象wp1wp2strWord成员,然后按照您的逻辑进行操作。