jeudi 27 septembre 2018

Using const_reverse_iterator instead of reverse_iterator and getting nasty compiler warnings and errors

I am currently in the process of learning C++ and encounter an issue while using

std::string::reverse_iterator 

to reverse a string. I get nasty compiler errors when trying to run the function below. However, when I switch to using,

std::string::const_reverse_iterator

,the code compiles and runs successfully. Why is this the case, especially when the documentation for the language says that reverse iterators can be declared and used. What if I need to say, remove elements from a string while looping through it in reverse, and want to use a reverse iterator? A

const_reverse_iterator

surely would not suffice in this case. Any help would be much appreciated. :)

std::string reverse(const std::string &str)
{
    std::string::reverse_iterator r_iter;
    std::string result;

    for (r_iter = str.rbegin(); r_iter < str.rend(); r_iter++) {
            result += (*r_iter);
    }

    return result;
}

Aucun commentaire:

Enregistrer un commentaire