Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <unordered_set>
- #include <iostream>
- #include <string>
- #include <vector>
- #include <algorithm>
- #include <iterator>
- class Comparable {
- public:
- int _weight;
- std::string _name;
- std::string _surname;
- Comparable(const int weight, const std::string &name, const std::string &surname) {
- _weight = weight;
- _name = name;
- _surname = surname;
- }
- Comparable(Comparable &&other) = default;
- Comparable &operator=(const Comparable &other) = default;
- Comparable &operator=(Comparable &&other) = default;
- };
- class Hasher {
- public:
- size_t operator() (const Comparable &c) const {
- return c._name.size() + c._surname.size() << (c._weight & 0x0f);
- }
- };
- class SetComparator {
- public:
- enum class ComparatorType {
- CompareByName,
- CompareBySurname,
- CompareByWeight
- };
- SetComparator(ComparatorType type) {
- _type = type;
- }
- bool operator() (const Comparable &first, const Comparable &second) const {
- switch (_type) {
- case ComparatorType::CompareByName:
- return first._name == second._name;
- break;
- case ComparatorType::CompareBySurname:
- return first._surname == second._surname;
- break;
- case ComparatorType::CompareByWeight:
- return first._weight == second._weight;
- break;
- }
- }
- private:
- ComparatorType _type;
- };
- std::ostream &operator<<(std::ostream &stream, const Comparable &c) {
- stream << c._name << " - " << c._surname << " - " << c._weight << std::endl;
- return stream;
- }
- void main() {
- std::vector<Comparable> data{
- Comparable(10, "Andrew", "Malkin"),
- Comparable(12, "Ivan", "Gusakov"),
- Comparable(10, "Shamil", "Huil"),
- Comparable(15, "Ivan", "Chkalov"),
- Comparable(15, "Maxim", "Huil")
- };
- SetComparator nameComparator(SetComparator::ComparatorType::CompareByName);
- SetComparator weightComparator(SetComparator::ComparatorType::CompareByWeight);
- Hasher hasher;
- std::unordered_set<Comparable, Hasher, SetComparator> set(20, hasher, nameComparator);
- std::unordered_set<Comparable, Hasher, SetComparator> secondSet(20, hasher, weightComparator);
- set.max_load_factor(0.8f);
- secondSet.max_load_factor(0.8f);
- std::cout << "Inserting first set: " << std::endl;
- std::copy(data.cbegin(), data.cend(), std::inserter<decltype(set)>(set, set.begin()));
- std::copy(set.cbegin(), set.cend(), std::ostream_iterator<Comparable>(std::cout));
- std::cout << "Inserting second set: " << std::endl;
- std::copy(data.cbegin(), data.cend(), std::inserter<decltype(secondSet)>(secondSet, secondSet.begin()));
- std::copy(secondSet.cbegin(), secondSet.cend(), std::ostream_iterator<Comparable>(std::cout));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement