This ObjectSet
container adds new Object
s with lowest possible unique ID. My implementation uses std::set
for its sorting, but this convenience may not be required.
My two main questions are:
Is
std::set
generally a good and preferred solution for this problem?In case of using
std::set
, canObjectSet::minId
be implemented with use of standard algorithms?
Code:
#include <iostream>
#include <set>
#include <string>
class Object
{
std::uint32_t id_;
public:
explicit Object(std::uint32_t id) : id_(id) {}
std::uint32_t const& id() const
{
return id_;
}
std::string name() const
{
return "Object" + std::to_string(id_);
}
bool operator<(Object const& other) const
{
return id_ < other.id_;
}
};
class ObjectSet : std::set<Object>
{
public:
void addObject()
{
insert(Object(minId()));
}
void removeObject(std::uint32_t id)
{
erase(Object(id));
}
std::uint32_t minId() const
{
if(empty())
return 1;
for(auto it1 = begin(), it2 = it1++; it1 != end(); ++it1, ++it2)
if(it1->id() != it2->id() + 1)
return it2->id() + 1;
return rbegin()->id() + 1;
}
using Base = std::set<Object>;
using Base::begin;
using Base::cbegin;
using Base::rbegin;
using Base::crbegin;
using Base::end;
using Base::cend;
using Base::rend;
using Base::crend;
};
int main()
{
ObjectSet objects;
objects.addObject();
objects.addObject();
objects.addObject();
objects.removeObject(2);
objects.addObject();
for(auto const& object : objects)
std::cout << object.name() << std::endl;
}