简体   繁体   English

在 C++ 中反向迭代字符串的字符

[英]Reverse Iterating Over Characters of String in C++

I want to print the reverse of a string我想打印一个字符串的反面

#include <iostream>
#include <string>
using namespace std;
int main()
{
    string str = "no", str1 = "yes";
    for (int i = str.size() - 1; i >= 0; i--)
        cout << str[i];
    for (int j = str1.size(); j >= 0; j--) //without minus one
        cout << str1[j];
}

What is the difference between the two loops ?这两个循环有什么区别? When it gives null pointer ?什么时候给出空指针?

See here :这里

在此处输入图片说明

So in C++11 this should be fine as it prints the null character, but in earlier versions, it could also be undefined behavior.所以在 C++11 中这应该没问题,因为它打印空字符,但在早期版本中,它也可能是未定义的行为。 Which means that anything could happen, including any kind of error, or even the expected behavior.这意味着任何事情都可能发生,包括任何类型的错误,甚至是预期的行为。

If it's working on your system but not on the system you're doing the exam on, it's probably because the exam system uses an old version where it's undefined behavior.如果它在您的系统上运行,但在您进行考试的系统上不起作用,则可能是因为考试系统使用的是未定义行为的旧版本。 Or it is undefined behavior on both systems but just manifests in different ways.或者它在两个系统上都是未定义的行为,只是以不同的方式表现出来。

@Blaze already answered why accessing str[str.size()] might cause problems. @Blaze 已经回答了为什么访问str[str.size()]可能会导致问题。

One way to avoid these problems when iterating array-like is to use iterator - in your case reverse_iterator would do the trick:在迭代类似数组时避免这些问题的一种方法是使用iterator - 在您的情况下reverse_iterator可以解决问题:

std::string::reverse_iterator itr = str1.rbegin();

while (itr != str1.rend())
   std::cout << *itr++;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM