C++如何向后打印字符串?

oce*_*800 1 c++ string

我试图std::string用这样的迭代器向后打印:

std::string back = "hello";
for(std::string::iterator it=back.end(); it!=back.begin(); --it)
{
    std::cout << (*it);
}
Run Code Online (Sandbox Code Playgroud)

但输出只会打印出来:

olle
Run Code Online (Sandbox Code Playgroud)

为什么不打印h?我尝试了几种不同的东西并玩弄它,但我似乎无法弄清楚原因.任何帮助将不胜感激,谢谢!:)

Ale*_*exD 13

std::string back = "hello";
for (std::string::reverse_iterator it = back.rbegin(); it != back.rend(); ++it)
{
    std::cout << (*it);
}
Run Code Online (Sandbox Code Playgroud)


Sam*_*hik 6

std::string::iterator it=back.end();
Run Code Online (Sandbox Code Playgroud)

it被初始化为end().然后,在循环内部:

std::cout << (*it);
Run Code Online (Sandbox Code Playgroud)

由于itis 的初始值end(),解除引用它是未定义的行为,具有不可预测的结果.

正确的方法是在取消引用it 之前递减:

for(std::string::iterator it=back.end(); it!=back.begin(); )
{
    --it;
    std::cout << (*it);
}
Run Code Online (Sandbox Code Playgroud)


pet*_*ltz 5

如果你不想要for循环:

#include <algorithm>

std::string string_back = "hello";
std::reverse(string_back.begin(), string_back.end());
std::cout << string_back; // prints 'olleh'
Run Code Online (Sandbox Code Playgroud)