STL iterators can be char*

Tuesday 10 December 2002This is 22 years old. Be careful.

Here’s a handy fact about the C++ Standard Template Library that I didn’t know: a char* (or any other pointer) is a valid iterator. This is because it is all templates, and iterators are anything that supports increment (++), and indirection (*); and whose elements support things like equality (==) and assignment (=).

For example, to search one chunk of memory for another chunk:

#include <algorithm>

char * pBuf = /* start of buffer to search */
char * pBufEnd = /* just past end of buffer */
char * pFind = /* data to find */
char * pFindEnd = /* just past end of data */

char * pFound = std::search(pBuf, pBufEnd, pFind, pFindEnd);

Just be careful: if the data isn’t found, search returns pBufEnd, not NULL!

Found this in the C++ forum at Experts Exchange.

Comments

Add a comment:

Ignore this:
Leave this empty:
Name is required. Either email or web are required. Email won't be displayed and I won't spam you. Your web site won't be indexed by search engines.
Don't put anything here:
Leave this empty:
Comment text is Markdown.