【发布时间】:2018-02-27 11:26:15
【问题描述】:
我想用地图创建一个简单的数据存储,
map<int , Person> people;
人在哪里
class Person
{
string name;
int age;
public:
Person() : name("noname"), age(0) {}
Person(string name, int age) : name(name), age(age) {}
void print()
{
cout << "| " << name << " | " << age << endl;
}
};
我在 map::find() 函数中引用 people.name 时遇到问题。可能我只是不知道正确的语法,我找不到答案。它可能看起来应该是这样的,但 name 是 Person 类的元素,所以我想它应该会给我一个错误。
if (people.find(name) != people.end())
{
people.erase(name);
cout << name << " removed from data base" << endl;
}
else
{
cout << name << " not found" << endl;
}
抱歉我的无知,但我最近才开始编程,这就是为什么我不知道基本语法并且有时会感到困惑。
【问题讨论】:
-
请提供minimal reproducible example。例如,您从哪里拨打
find?你有错误吗?如果是这样,请将其复制粘贴到问题中。您是否期望一个,但没有得到它,请解释为什么您期望它是一个错误。 -
请查看此C++ books 列表。
-
std::map可能不是您要查找的数据结构。 -
你有没有想过如果你有多个同名的人会发生什么?
-
@KillzoneKid 感谢您指出这一点。我想将键值与特定人的某个 id 号连接起来,在这种情况下 erase 条件必须确保要删除哪个人。