I am working on a requirement where requests should have unique number from -2 to -101 inclusive, i.e., there are unique 100 requests at a time. If there are more than 100 requests at a given time then I should send error. Initially I have no requests. Once I sent requests I will take unique number say -2 , -3 and so on. Here requirement is that I may get command from client don’t sent request to server for example -2 so I should delete this request and I should reuse this number for future request.
What is the best way to implement this in C++?
Also, I am not supposed to use Boost.
You have to maintain a collection of unused ids at least. Additionally I would throw in a lookup table to verify that an id was handed out (for robustness). For both, I would suggest to use an
std::vector, not a list.First, store the unused collection in an
std::vector<int>, which you can very easily initialise:Additionally, you may want to keep track of the used ids, so you can verify if they were handed out; I’d use an
std::vector<bool> used;member for that, which you can initialise simply withused(MAX_ID - MIN_ID +1)as its values will all default tofalseinitially. Of course, you can makeusedalso abitsetbut note that this would require the distance fromMIN_IDtoMAX_IDto be known at compile time.Handing out stuff is pretty simple from there:
And releasing them, also:
Note that no reallocations take place! The vector will keep its size and neither
getIdnorreleaseIdwill require expensive calls tomallocorfreecontrary to an approach using a list.