Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bidirectional iterator from char * buffer with size

I can't seem to be able to find an easy simple solution, how to get bidirectional iterator from char *buffer with defined bufferSize. I don't want to copy the buffer to std::string (too expensive), I just want something like std_whatever::buffer_wrapper myWrappedBuffer(myBuffer, mySize); and then use myWrappedBuffer.begin() and myWrappedBuffer.end() in <algorithm> functions. What is the simplest way to do that? I really don't want to implement the iterator myself. I know there is boost::string_ref and maybe std::string_view, but I don't want to use boost just for this and can't use c++17.

like image 958
tach Avatar asked Jul 04 '26 05:07

tach


1 Answers

char *b=buffer;

This is your beginning iterator.

char *e=buffer+buffersize;

This is your ending iterator.

Plain, garden variety pointers meet all requirements of not just bi-directional, but random access iterators, and can generally be used anywhere any kind of an iterator is required, and they'll work just like one. All (well-written) iterator-based templates will work with pointers just fine.

You can even feed them to std::iterator_traits, and get meaningful results. Try it yourself and see what happens.

like image 65
Sam Varshavchik Avatar answered Jul 05 '26 19:07

Sam Varshavchik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!