c++stringiteratorreverse-iterator

I have a question about 'push_back()' with reverse_iterator


#include<string>
#include<iterator>
#include<vector>
#include<iostream>

int main(){

    std::string str = "abc";
    std::string str2 = str;
    std::vector<int>::reverse_iterator rit = str.rbegin();
    for(rit+1; rit != str.rend(); rit++){
        str2.push_back('*rit');
    }
    std::cout << str2 << std::endl;
}

I expected the output to be 'abcba', but there seems to be an error in push_back(). Somebody help me T_T


Solution

  • For starters there is a typo (or you wanted to highlight the expression)

    str2.push_back('*rit');
    

    It seems you mean

    str2.push_back( *rit);
    

    This declaration

    std::vector<int>::reverse_iterator rit = str.rbegin();
    

    does not make a sense. The declared object and the right expression used as an initializer have different types and there is no implicit conversion between them.

    What you need is the following

        std::string str = "abc";
        std::string str2 = str;
    
        str2.append( str.rbegin(), str.rend() );
    
        std::cout << str2 << '\n';
    

    Or you could write

        std::string str = "abc";
        std::string str2 = str;
    
        for (std::string::reverse_iterator it = str.rbegin(); it != str.rend(); ++it)
        {
            str2.push_back( *it );
        }
    
        std::cout << str2 << '\n';
    

    Or the for loop could be written like

    for (auto it = str.rbegin(); it != str.rend(); ++it)