#第一次尝试哈希结构,写了一个代码,立刻就错了!
代码如下:
#include
#include
// Data Structure to store a Student Information
struct Student
{
int id;
const char* name;
Student(int Id, const char* Name) : id(Id), name(Name) {}
};
// Function to print the student details
void print_student(Student s)
{
std::cout << "ID: " << s.id << ", Name: " << s.name << std::endl;
}
// Driver Code
int main()
{
// Creating a unordered map with Student structure
// as key and marks as value
std::unordered_mapint> studentMarksMap;
// Inserting values in studentMarksMap
studentMarksMap.insert({ { 1, "Martin" }, 84});
studentMarksMap.insert({ { 2, "Andrew" }, 87});
studentMarksMap.insert({ { 3, "John" }, 98});
// Traversing an unordered map
for (auto itr = studentMarksMap.begin(); itr != studentMarksMap.end(); itr++)
{
print_student(itr->first);
std::cout << "\tMarks: " << itr->second << std::endl;
}
return 0;
}
报错信息:
如楼上所说, C++无序容器对于非基本类型需要定义hash函数以及operator==, 补充一个方法, 对于不想用仿函数的可用lambda方法
#include <iostream>
#include <unordered_map>
// Data Structure to store a Student Information
struct Student
{
Student(int Id, const char *Name)
: id(Id)
, name(Name)
{}
// Function to print the student details
void print_student() const
{
std::cout << "ID: " << id << ", Name: " << name << std::endl;
}
auto operator==(const Student &rhs) const -> bool
{
if (this != &rhs)
{
return id == rhs.id && (strcmp(name, rhs.name) == 0);
}
return true;
}
[[nodiscard]] auto getid() const -> int
{
return id;
}
[[nodiscard]] auto getname() const -> const char *
{
return name;
}
private:
int id = 0;
const char *name = nullptr;
friend std::hash<Student>;
};
// namespace std
//{
// template <>
// struct hash<Student>
//{
// auto operator()(const Student &stu) const -> size_t
// {
// return std::hash<int>()(stu.id) ^
// std::hash<std::string>()(std::string(stu.name));
// }
// };
// } // namespace std
// Driver Code
int main()
{
auto hash = [](Student stu) -> size_t {
return std::hash<int>()(stu.getid()) ^
std::hash<std::string>()(std::string(stu.getname()));
};
// Creating a unordered map with Student structure
// as key and marks as value
std::unordered_map<Student, int, decltype(hash)> studentMarksMap(10, hash);
// Inserting values in studentMarksMap
studentMarksMap.insert({{1, "Martin"}, 84});
studentMarksMap.insert({{2, "Andrew"}, 87});
studentMarksMap.insert({{3, "John"}, 98});
// Traversing an unordered map
for (auto &itr : studentMarksMap)
{
itr.first.print_student();
std::cout << "\tMarks: " << itr.second << std::endl;
}
return 0;
}
不知道你这个问题是否已经解决, 如果还没有解决的话: