Skip to content

Instantly share code, notes, and snippets.

@bodokaiser
Created June 30, 2018 17:09
Show Gist options
  • Select an option

  • Save bodokaiser/b9a1144586fdb6426baf9a63d57c2c32 to your computer and use it in GitHub Desktop.

Select an option

Save bodokaiser/b9a1144586fdb6426baf9a63d57c2c32 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
struct Person {
std::string first_name;
std::string last_name;
int age;
};
std::ostream& operator<<(std::ostream& stream, const Person p) {
stream << p.first_name << " " << p.last_name << " (" << p.age << ")";
return stream;
}
struct Student {
size_t id;
Person person;
};
// required by set
bool operator<(const Student lhv, const Student rhv) {
return lhv.id < rhv.id;
}
// required by unordered_set
bool operator==(const Student lhv, const Student rhv) {
return lhv.id == rhv.id;
}
// required by unoredered_set
namespace std {
template <> struct hash<Student> {
size_t operator()(const Student& student) const {
std::hash<size_t> hash;
return hash(student.id);
}
};
}
int main() {
std::map<size_t, Person> people1 = {
{1001, {"Alice", "Cooper", 69}},
{1021, {"Bodo", "Kaiser", 23}},
{1221, {"Angela", "Merkel", 70}}
};
std::cout << "map:" << std::endl;
for (auto const& [id, person] : people1) {
std::cout << person << std::endl;
}
std::unordered_map<size_t, Person> people2 = {
{1001, {"Alice", "Cooper", 69}},
{1021, {"Bodo", "Kaiser", 23}},
{1221, {"Angela", "Merkel", 70}}
};
std::cout << "unordered_map:" << std::endl;
for (auto const& [id, person] : people2) {
std::cout << person << std::endl;
}
std::set<Student> students1 = {
{1001, {"Homer", "Simpson", 69}},
{1021, {"Carl", "Johnson", 23}},
{1221, {"Nico", "Bellic", 70}}
};
std::cout << "set:" << std::endl;
for (auto const& student : students1) {
std::cout << student.person << std::endl;
}
std::unordered_set<Student> students2 = {
{1001, {"Homer", "Simpson", 69}},
{1021, {"Carl", "Johnson", 23}},
{1221, {"Nico", "Bellic", 70}}
};
std::cout << "unordered_set:" << std::endl;
for (auto const& student : students2) {
std::cout << student.person << std::endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment