1

I have stumbled upon something that has me utterly confused.

std::reverse() takes bidirectional iterators as arguments into the function, but when I pass pointers to the function, it seems to work fine and actually reverse the string.

void reverseFour(char* str) {
    reverse(str, str + strlen(str));
}

int main {
    char *str = "hello";
    str += '/0';
    reverseFour(str);
}

So, my question is, how is this possible? Bidirectional iterators are not pointers, right?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 7
    no but pointers are bidirectional iterators, the iterator interface was chosen to be compatible with pointer syntax – john Feb 27 '18 at 21:43
  • 3
    cows are animals does not mean animals are cows. – juanchopanza Feb 27 '18 at 21:43
  • 3
    Pointers are even random access iterators, at least when they point to elements of an array. – nwp Feb 27 '18 at 21:44
  • @nwp -- and any pointer that you're using as an iterator has to point into an array. If it doesn't, you can't increment it or decrement it. – Pete Becker Feb 27 '18 at 21:44
  • And pointers can also be contiguos iterators (C++17) – AdvSphere Feb 27 '18 at 21:46
  • If you want to show the code works fine, at least you need to post valid code. Your code has too many errors. – llllllllll Feb 27 '18 at 21:47
  • 2
    The code shown has **undefined behavior**, because `main()` is passing a pointer to a string literal to `std::reverse()` (and a non-const pointer at that, which is not allowed in C++11, unless you tell the compiler to disable that restriction). `reverse()` will try to write to read-only memory, which will likely crash the app. To make the code valid, use `char str[] = "hello";` instead. – Remy Lebeau Feb 27 '18 at 21:56

1 Answers1

7

A pointer is, in fact, a kind of RandomAccessIterator. This is even better than a BidirectionalIterator, in that any algorithm that requires a BidirectionalIterator will also accept a RandomAccessIterator, including pointers.

This is quite deliberate, and very useful.

There does, of course, exist other kinds of iterators, particularly some types that are dedicated to being just iterators and nothing more (you'll get these from std::set and std::map, for example). But the concept of an Iterator is something that C++ deliberately keeps rather general.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055