【发布时间】:2017-08-02 17:09:01
【问题描述】:
我正在尝试创建一个包含联系人列表的程序,用户可以在其中根据电话号码搜索联系人的姓名。很抱歉包含这么多代码,但理解我的问题是必要的:
#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。 Sams 每天一小时自学 C++。第 8 版,印第安纳波利斯,印第安纳州,Sams,2017 年。
【问题讨论】: