Commit 1a83adfe authored by Alexander Hirsch's avatar Alexander Hirsch

Add person_id example

parent 7f875dd6
CXXFLAGS = -std=c++17 -Wall -Wextra -O2
OUT = person_id
all: $(OUT)
clean:
$(RM) $(OUT)
.PHONY: all clean
// This example illustrates the use of IDs for referencing objects. IDs serve as
// a viable alternative to smart pointers, raw pointers, and values.
//
// The focus of this example lies on a clean and straight forward interface
// *and* implementation.
#include <algorithm>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
// Person itself is just an ID.
using Person = int;
// Renaming the original struct to PersonData is a sensible change.
struct PersonData {
std::string firstName;
std::string lastName;
int age;
};
// This database generates Person IDs and stores the corresponding PersonData.
class PersonDatabase {
public:
Person createPerson(const PersonData &personData)
{
m_personData.push_back(personData);
return m_personData.size() - 1;
}
const PersonData &getPersonData(Person person) const { return m_personData.at(person); }
private:
// A simple vector will do, the resulting Person ID is simply the index of
// the corresponding PersonData. This enables fast lookups.
std::vector<PersonData> m_personData;
};
class Room {
public:
Room(int id, size_t capacity) : m_id(id), m_capacity(capacity) {}
bool enter(Person person)
{
if (m_peopleInside.size() >= m_capacity) {
return false;
}
m_peopleInside.push_back(person);
return true;
}
void exit(Person person)
{
const auto it = std::find(m_peopleInside.begin(), m_peopleInside.end(), person);
if (it != m_peopleInside.end()) {
m_peopleInside.erase(it);
}
}
const std::vector<Person> &peopleInside() const { return m_peopleInside; }
private:
int m_id;
size_t m_capacity;
std::vector<Person> m_peopleInside;
};
int main()
{
PersonDatabase database;
const auto mike = database.createPerson({"Mike", "Smith", 24});
const auto jane = database.createPerson({"Jane", "Saw", 28});
Room room{128, 42};
room.enter(mike);
room.enter(jane);
for (auto person : room.peopleInside()) {
std::cout << "Hallo " << database.getPersonData(person).firstName << "\n";
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment