-
Notifications
You must be signed in to change notification settings - Fork 0
/
garage.cpp
74 lines (60 loc) · 1.19 KB
/
garage.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/*
Some sort of garage class allowing multiple car add
while only unique ids are accepted
https://ideone.com/8yUyHV
*/
#include <iostream>
#include <unordered_set>
#include <initializer_list>
class Car
{
private:
int id;
public:
Car(int id) : id(id) {};
int getId() const { return id; }
};
struct Hash
{
std::size_t operator()(Car const &car) const
{
return std::hash<int>{}(car.getId());
};
};
struct Equal
{
bool operator()(Car const &car1, Car const &car2) const
{
return car1.getId() == car2.getId();
};
};
class Garage
{
private:
std::unordered_set<Car, Hash, Equal> allcars;
public:
Garage() = default;
void addCars(std::initializer_list<Car> cars)
{
for (auto car : cars)
allcars.insert(car);
}
friend std::ostream &operator<<(std::ostream &os, Garage const &garage)
{
for (auto const &car : garage.allcars)
os << "Car id: " << car.getId() << std::endl;
return os;
}
};
int main()
{
Garage garage;
Car car4(4);
std::cout << "adding 3 cars" << std::endl;
garage.addCars({ 1,2,3,3,3,3,1,2,3 });
std::cout << garage << std::endl;
std::cout << "adding 1 more" << std::endl;
garage.addCars({ car4, car4, car4 });
std::cout << garage << std::endl;
return 0;
}