JBentley
JBentley

Reputation: 6260

Can a raw pointer be passed to a template function expecting an iterator?

Can raw pointers be passed to template functions expecting iterators? Am I right in thinking that an iterator is just a class which overrides the pointer-related operators (e.g. *, ++, etc.), or do iterators expose any additional interface that pointers do not? To put it another way, do pointers "look like" iterators?

Example:

I want to use boost::algorithm::knuth_morris_pratt_search (documentation here).

My corpus (string to be searched) and pattern (string being looked for) are simply bytes in memory - I have a pointer containing the start address, and the length in bytes. For the sake of the argument, let's say it's a c-style string.

According to the documentation, the knuth_morris_pratt_search function requires me to pass in start and end iterators for both the corpus and the pattern.

Function I wish to use:

template <typename patIter, typename corpusIter>
corpusIter knuth_morris_pratt_search (
        corpusIter corpus_first, corpusIter corpus_last,
        patIter pat_first, patIter pat_last );

Can I do this?

// Assume these are initialized:
char* c;
int cLength;
char* p;
int pLength;

char* result = knuth_morris_pratt_search<char*, char*>
   (c, c + cLength, p, p + pLength);

Upvotes: 4

Views: 168

Answers (1)

Matteo Italia
Matteo Italia

Reputation: 126777

Am I right in thinking that an iterator is just a class which overrides the pointer-related operators (e.g. *, ++, etc.),

You are correct; pointers to data stored in arrays match the requirements for random access iterators, i.e. the most "complete" iterator type, so you can use them in substantially any standard library algorithm.

I don't have the standard at hand for the full reference about random access iterators, but see e.g. here; also, here is a nice diagram with the various "types" of iterators.

Upvotes: 5

Related Questions