尝试使用自定义排序创建std::map

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

本文关键字:创建 std 排序 map 自定义      更新时间:2023-10-16

我正在回答一本初学者c++书中的问题。我正在做一个关于std::map的部分。问题是创建一个带有排序谓词的映射,该映射需要是一个自定义结构(wordProperty)作为键,定义(string)作为值。

我得到错误;

错误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.0vcincludexutility 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成员,并遵循您的逻辑。