Filippo
Filippo

Reputation: 157

Iterator over a unique element without construction a container

I have a framework which has requires as input an iterator. But sometime, I have a single element, so constructing a container seems like too much work.

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 that already exist in the standard library or boost?

Upvotes: 3

Views: 122

Answers (2)

SergeyA
SergeyA

Reputation: 62563

Although there is a answer already, I'd suggest another approach: just add another overload to your call, which accepts an element itself, and make your iterator version calling the single element function in a loop.

This will make the code more straightforward, and have an added benefit of better optimized code in non-inlined cases.

Upvotes: 1

NathanOliver
NathanOliver

Reputation: 180510

A single element can be thought of as an array of size one. So if we use that then a pointer to the object would be a pointer(iterator) to the start of the array and a pointer to one past then end of the array would just be that pointer incremented once. So what you can do is use

call(&object, &object + 1)

And now you will only process the single object.

Upvotes: 4

Related Questions