behavior of reverse_iterator with const char []

2

Having the following objects:

const char      a[]{"abcdefghij"}; // Arreglo de caracteres (longitud 11)
const std::string s{"abcdefghij"}; // basic_string<char> estandar

I expected these loops to behave the same:

// 1) Muestra NADA, esperaba "jihgfedcba"
for (auto begin = std::rbegin(a), end = std::rend(a); begin != end; ++begin)
    std::cout << *begin;
std::cout << std::endl;
// 2) Muestra "jihgfedcba", tal y como esperaba
for (auto begin = std::rbegin(s), end = std::rend(s); begin != end; ++begin)
    std::cout << *begin;
std::cout << std::endl;

But showing the character array shows nothing while displaying the string shows the expected output.

Displaying the array of characters also affects how the string is displayed: if loop 1 is written before loop 2 the program shows nothing but writing loop 2 before the one shows a single jihgfedcba .

I have noticed that modifying the return value of std::rbegin(a) solves the problem:

// Muestra "jihgfedcba", tal y como esperaba
// notese el ++!!
for (auto begin = ++std::rbegin(a), end = std::rend(a); begin != end; ++begin)
    std::cout << *begin;
std::cout << std::endl;

// Muestra "jihgfedcba", tal y como esperaba
for (auto begin = std::rbegin(s), end = std::rend(s); begin != end; ++begin)
    std::cout << *begin;
std::cout << std::endl;

Why is this happening?

    
asked by PaperBirdMaster 11.11.2016 в 11:33
source

1 answer

2
const char      a[]{"abcdefghij"};

It really becomes

const char      a[]{ 'a','b',...,'i','j','
const char      a[]{ 'a','b','c','d','e','f','g','h','i' };
'};

If you call std::rbegin , what it does is point to the character '\ 0'. What can happen with this (which is more dependent on the console environment) is that the good does not print anything or, as in my case, print a space before starting with the expected sequence.

Why this behavior? Basically because really char * does not impose restrictions on what it is going to store. You do not have to make the string end with '\ 0' (this is only necessary if you are going to use the string manipulation functions of the standard library).

Another possible solution could be the following:

const char      a[]{"abcdefghij"};

This prevents the compiler from adding the null character at the end of the sequence, so you can avoid that initial pre-increment.

    
answered by 11.11.2016 / 12:00
source