電話番号に基づいて連絡先の名前を検索できる連絡先の一覧を持つプログラムを作成しようとしています。そんなにコードを含むため申し訳ありませんが、それは私の問題を理解するために必要である:find()を使用したIteratorからstd :: setは機能しません。何がうまくいかないの?
#include <iostream>
#include <string>
#include <set>
using namespace std;
struct ContactItem
{
string name;
string phoneNumber;
string displayAs;
ContactItem(const string inName, const string inNumber) : name(inName), phoneNumber(inNumber)
{
displayAs = name + ": " + phoneNumber;
}
bool operator== (const ContactItem& searchParameter) const
{
return (this->phoneNumber == searchParameter.phoneNumber);
}
bool operator< (const ContactItem& compareResult) const
{
return (this->name < compareResult.name);
}
operator const char*() const
{
return displayAs.c_str();
}
};
int main()
{
//Initialize a set and populate it with contacts of type ContactItem
set<ContactItem> contactBook;
contactBook.insert(ContactItem("Sally", "123654864"));
contactBook.insert(ContactItem("Joe", "8435102654"));
contactBook.insert(ContactItem("Steve", "8135691234"));
contactBook.insert(ContactItem("Alice", "8432489425"));
//Search for a contact's name by only being given their number
cout << "Please give the number of one contact whose name you would like to know: " << endl;
string userNumber;
getline(cin, userNumber);
auto findNumber = contactBook.find(ContactItem("", userNumber));
if (findNumber != contactBook.end())
cout << "The name of the contact whose number matches the phone number given is: " << (*findNumber).name << endl;
else
cout << "Contact not found" << endl;
return 0;
}
私の問題は、常にラインauto findNumber = contactBook.find(userNumber);
であると思われます。このコードを実行するたびに、「連絡先が見つかりません」というメッセージが表示されます。私は何が間違っているのか分かりません。それはoperator==
の私の再定義ですか?
上記のコードはRao、Siddharthaからインスピレーションを受けています。 サムズは1時間に1時間でC++を教える第8版、インディアナ州インディアナポリス、サムス、2017年
'演算子'は[厳密な弱い順序](https://www.sgi.com/tech/stl/StrictWeakOrdering.html)を実装しなければならないという価値があるかもしれません。初心者はしばしば間違っています。 –
この回答はすべて当てはまりますが、実際に問題は解決されません。コンパレータを変更しても部分的に一致するアイテムは見つかりません。 –
@AdrianMcCarthy名前を無視する比較器を使用し、この 'std :: set'のために電話を比較するだけで問題を解決できます。 – Slava