Commit b30744b44c00b4dcfe9deb015a974d21951bcb32
1 parent
f107c09e
Unordered_set with closure as a hash function
Showing
3 changed files
with
57 additions
and
2 deletions
examples09/07-closures/employee.h
0 → 100644
1 | +#ifndef __EMPLOYEE_H__ | |
2 | +#define __EMPLOYEE_H__ | |
3 | +#include <string> | |
4 | +#include <iostream> | |
5 | + | |
6 | +struct Employee | |
7 | +{ | |
8 | + std::string FirstName, LastName, ID; | |
9 | + Employee (const std::string & fn, const std::string & ln, | |
10 | + const std::string & I):FirstName (fn), LastName (ln), ID (I) | |
11 | + { | |
12 | + }; | |
13 | + friend std::ostream& operator<< (std::ostream & o, const Employee & e) | |
14 | + { | |
15 | + o << e.FirstName << " " << e.LastName << " " << e.ID; | |
16 | + return o; | |
17 | + }; | |
18 | + | |
19 | + bool operator==(const Employee& o) const | |
20 | + { | |
21 | + return (FirstName == o.FirstName) && (LastName == o.LastName) && (ID == o.ID); | |
22 | + } | |
23 | +}; | |
24 | +#endif /* __EMPLOYEE_H__ */ | ... | ... |
examples09/07-closures/makefile
1 | -all: fun1 fun2 fun3 fun4 fun5 | |
1 | +all: fun1 fun2 fun3 fun4 fun5 unordered_set3 | |
2 | 2 | |
3 | 3 | fun1: fun1.o |
4 | 4 | g++ -g -Wall $^ -o $@ |
... | ... | @@ -30,7 +30,14 @@ fun5.o: fun5.cpp |
30 | 30 | fun5: fun5.o |
31 | 31 | g++ -g -Wall $^ -o $@ |
32 | 32 | |
33 | + | |
34 | +unordered_set3.o: unordered_set3.cpp | |
35 | + g++ -std=c++2a -g -c -Wall $< -o $@ | |
36 | + | |
37 | +unordered_set3: unordered_set3.o | |
38 | + g++ -g -Wall $^ -o $@ | |
39 | + | |
33 | 40 | .PHONY: clean |
34 | 41 | |
35 | 42 | clean: |
36 | - -rm fun1.o fun1 fun2.o fun2 fun3.o fun3 fun4.o fun4 fun5.o fun5 | |
37 | 43 | \ No newline at end of file |
44 | + -rm fun1.o fun1 fun2.o fun2 fun3.o fun3 fun4.o fun4 fun5.o fun5 unordered_set3.o unordered_set3 | |
38 | 45 | \ No newline at end of file | ... | ... |
examples09/07-closures/unordered_set3.cpp
0 → 100644
1 | +#include <functional> | |
2 | +#include <unordered_set> | |
3 | +using namespace std; | |
4 | +#include "employee.h" | |
5 | + | |
6 | +int main() { | |
7 | + Employee Ben("Ben", "Keller", "000-00-0000"); | |
8 | + Employee Bill("Bill", "McQuain", "111-11-1111"); | |
9 | + Employee Dwight("Dwight", "Barnette", "888-88-8888"); | |
10 | + | |
11 | + auto empHash = [](const Employee &o) { | |
12 | + return std::hash<std::string>()(o.FirstName) ^ | |
13 | + (std::hash<std::string>()(o.LastName) << 1) ^ | |
14 | + (std::hash<std::string>()(o.ID) << 2); | |
15 | + }; | |
16 | + | |
17 | + unordered_set<Employee, decltype(empHash)> S; | |
18 | + S.insert(Bill); | |
19 | + S.insert(Dwight); | |
20 | + S.insert(Ben); | |
21 | + | |
22 | + for (auto i : S) | |
23 | + cout << i << endl; | |
24 | +} | ... | ... |