C++ 在c+中向后迭代+;

C++ 在c+中向后迭代+;,c++,for-loop,iteration,C++,For Loop,Iteration,我的印象是,下面的代码将打印出“hello world”,但它根本不打印任何内容。为什么? 使用g++4.2.1和cl++3.2编译 void iterateBackwards(){ std::string hiThere = "dlrow olleh"; for ( int i = hiThere.length(); i == 0; i--) { std::cout << hiThere[i]; } } void iterateBackwa

我的印象是,下面的代码将打印出“hello world”,但它根本不打印任何内容。为什么? 使用g++4.2.1和cl++3.2编译

void iterateBackwards(){
    std::string hiThere = "dlrow olleh";
    for ( int i = hiThere.length(); i == 0; i--) {
        std::cout << hiThere[i];
    }
}
void iterateBackwards(){
std::string here=“dlrow olleh”;
对于(inti=heree.length();i==0;i--){

std::cout您的条件应该是
i>=0
,而不是
i==0
(当条件为
false
时,就会立即退出
for
循环,这在您的示例中就是如此)

此外,一旦您解决了这个问题,您也应该解决
i
的赋值问题,因为下标操作符接受基于零的索引;这意味着当
i==heree.length()
时,您将访问字符串的终止符字符,您可能对输出不感兴趣

这应该更好地发挥作用:

void iterateBackwards(){
    std::string hiThere = "dlrow olleh";
    for ( int i = hiThere.length() - 1; i >= 0; i--) {
        std::cout << hiThere[i];
    }
}
void iterateBackwards(){
std::string here=“dlrow olleh”;
对于(inti=heree.length()-1;i>=0;i--){

std::cout此外,for循环中的条件应该是

i >= 0
而不是

i == 0
这是因为只要是真的,for循环就会迭代,如果使用i==0,则为假

  • 循环中的条件必须是
    i>=0
    。否则程序将永远不会进入循环体——只要
    i==0
    为真,并且您将
    i
    设置为字符串的长度,它就会循环
  • <>代码> i <代码>应用<代码> Hith.Limthth.-(1)/代码>初始化。否则,将有未定义的行为——C++中的字符串和数组为0索引,即第一索引为“代码> 0”/代码>最后一个是“代码>大小”-1 <代码>(“<代码> Hith[长](-1)] < /COD>是 HID< <代码>的最后一个元素。 您应该查看C++迭代器:

    void iterateBackwards(){
        std::string hiThere = "dlrow olleh";
        for (auto it = hiThere.crbegin(); it != hiThere.crend() ; ++it) {
            std::cout << *it;
        }
    }
    
    void iterateBackwards(){
    std::string here=“dlrow olleh”;
    for(auto it=heree.crbegin();it!=heree.crend();++it){
    
    std::cout@AndyProwl已经给出了一个解决方案,我将在这里复制它,以便与我的方案进行比较:

    std::string hiThere = "dlrow olleh";
    for ( int i = hiThere.length() - 1; i >= 0; i--) {
        std::cout << hiThere[i];
    }
    
    std::string here=“dlrow olleh”;
    对于(inti=heree.length()-1;i>=0;i--){
    
    std::cout for循环在退出条件(
    i==0
    )为false时立即退出。如果要向后打印字符串,请使用:
    std::copy(heree.rbegin(),heree.rend(),std::ostream_迭代器(std::cout,”)
    程序没有未定义的行为。他从不访问任何元素,更不用说超出范围的元素了。@BenjaminLindley:对,我编辑了答案。谢谢。好的。但是,尽管该行为可能不是OP所追求的,但在第一次修复后将不会有未定义的行为。
    basic\u string
    有一个特殊的l提供
    运算符[]
    ,以便与常见的c字符串用法兼容。访问
    heree[heree.size()]
    是合法的,并返回对值为
    char()的字符的引用
    ,可能在字符串末尾,也可能不在字符串末尾。请参阅标准:
    21.4.5/1&2
    。如果您试图修改该值,则这是未定义的行为,但在此处不会执行。@BenjaminLindley:对。我将再次编辑。谢谢您的帮助。还有,请不要再烦学究了。
    std::string hiThere = "dlrow olleh";
    for (size_t i = hiThere.length(); i--; ) {
        std::cout << hiThere[i];
    }