我有一个简单的电话号码簿,但我想对其进行修改,以便我可以搜索姓氏列表,并且应该返回姓氏相同的名字。一个人可以有多个号码,并且一个号码可以属于一个以上的人(一个家庭成员)。一个电话号码通常可以包含非数字字符,例如,如果我在下面列出了这样的姓名
john williams
smart williams
hendrix james
drey williams
如果我输入威廉姆斯或搜索威廉姆斯,它应该返回
john williams
smart willams
drey williams
我想使用
Map<String,List<String>>.
class name {
string str;
public:
name() {
str = "";
}
name(string s) {
str = s;
}
string get() {
return str;
}
};
// Define less than relative to name objects.
bool operator<(name a, name b){
return a.get() < b.get();
}
class surname {
string str;
public:
surname() {
str = "";
}
surname(string s) {
str = s;
}
string get() {
return str;
}
};
int main()
{
map<name, surname> directory;
directory.insert(pair<name, surname>(name("James"), surname("williams")));
directory.insert(pair<name, surname>(name("Coz"), surname("williams")));
directory.insert(pair<name, surname>(name("James"), surname("trues")));
directory.insert(pair<name, surname>(name("Tni"),surname("mutton")));
// given a name, find number
string str;
cout << "Enter name: ";
cin >> str;
map<name, surname>::iterator p;
p = directory.find(name(str));
if(p != directory.end())
cout << "surname: " << p->second.get();
else
cout << "Name not in directory.\n";
system("pause");
return 0;
}
提前致谢
最佳答案
该映射是一个键/值对容器,这意味着您必须定义将要使用的键和将要使用的值,在这种情况下,您希望将姓氏用作键,并将与该姓氏相关的名称列表一个值。正如您已经注意到的,您可以通过向量映射来实现,其中向量是您的值:
std::map<std::string, std::vector <std::string> > directory;
这是您想要实现的一个可行示例(我替换了字符串的名称和姓氏结构,因为我看不到使用它们的意义,但是您可以根据需要将其改回)
#include <string>
#include <map>
#include <vector>
#include <ostream>
#include <iostream>
int main()
{
std::map<std::string, std::vector <std::string> > directory;
directory["williams"].push_back("James");
directory["williams"].push_back("Coz");
directory["trues"].push_back("James");
directory["mutton"].push_back("Tni");
// given a name, find number
std::string str;
std::cout << "Enter surname: ";
std::cin >> str;
std::map<std::string, std::vector <std::string> >::iterator p;
p = directory.find(str);
if(p != directory.end())
{
std::string key = p->first;
std::vector<std::string> names = p->second;
for (int i = 0; i < names.size(); ++i)
std::cout << key << " " << names[i] << std::endl;
}
else
{
std::cout << "Name not in directory.\n";
}
return 0;
}
对于输入威廉姆斯,它将输出:
Enter surname: williams
williams James
williams Coz
要为“ williams”添加更多名称,您只需要继续将名称推回该向量即可:
directory["williams"].push_back("Luis");
directory["williams"].push_back("Pedro");
directory["williams"].push_back("Juan");
希望能帮助到你。
关于c++ - 使用标准模板库列表或 vector 和 multimap 创建电话目录,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14025087/