Iterator over unique element without container construction
I have a structure that requires input as an iterator. But sometime I have one item, so creating the container seems to be too big.
T obj; // my unique object
std::vector<T> vec; // I want to avoid this
vec.push_back(T);
// Because the only use of the container is for this call
call(std::begin(vec), std::end(vec));
// I want to do something like that
call(BeginFakeSingletonIt<T>(obj), EndFakeSingletonIt<T>());
I could create a special type of iterator, but doesn't something like this already exist in the standard library or boost?
source to share
One element can be thought of as an array of size one. So if we use this, the object pointer will be a pointer (iterator) to the beginning of the array and a pointer to one past, and then the end of the array will only be that the pointer is incremented once. So what you can do is use
call(&object, &object + 1)
Now you will only be processing one object.
source to share
Although there is already an answer, I would suggest a different approach: just add another overload to your call that takes the element itself, and make your iterator version call one element function in a loop.
This will make the code simpler and will add the benefits of improved optimized code in unrelated cases.
source to share