简体   繁体   English

关于 C++ 中基于范围的 for 循环的困惑

[英]Confusion regarding range-based for loop in C++

This code takes a string and then write outs the even and odd-positioned characters of the string as 2 separate strings separated by a space.此代码获取一个字符串,然后将字符串的偶数和奇数位置的字符写出为由空格分隔的 2 个单独的字符串。 I have solved the problem using standard for loop.我已经使用标准 for 循环解决了这个问题。 But I am trying to use range-based for loop in it instead of the normal for loop (after getting fired up by Bjarne's 2017 CPPCON keynote).但我试图在其中使用基于范围的 for 循环而不是普通的 for 循环(在被 Bjarne 的 2017 CPPCON 主题演讲激怒之后)。 The normal for loop works fine and I have commented it in the following code-block.正常的 for 循环工作正常,我在以下代码块中对其进行了评论。

Problem is: The code compiles with g++ -std=c+11 command, but the even and odd strings are coming out garbled and reads like binary files.问题是:代码使用 g++ -std=c+11 命令编译,但偶数和奇数字符串出现乱码,读起来像二进制文件。 Can you please explain what I am doing wrong and exactly what is happening here?你能解释一下我做错了什么以及这里发生了什么吗? A clear explanation will be much appreciated.一个明确的解释将不胜感激。 Thank you.谢谢你。

    string S,even,odd;
    cout << "Enter a string:\n";
    cin.ignore();   // So that getline does not catch 
    //the eol character
    getline(cin,S);
    // for (int j=0; j<S.length(); j++){
    //     if(j==0 || j%2==0){even.push_back(S[j]);}
    //     else {odd.push_back(S[j]);}
    // }
    for (auto j : S){
        if(j==0 || j%2==0){even.push_back(S[j]);}
        else {odd.push_back(S[j]);}
    }
    cout << "You wrote: " << S <<'\n';
    cout << "Even(including 0) positioned character(s) 
    of " << S << " is(are) " << even <<'\n';
    cout << "Odd positioned character(s) of " << S << 
    " is(are) " << odd <<'\n';

The range-based for loop iterates over the elements of a container.基于范围的 for 循环迭代容器的元素。 'j' in your code is a character in the string, not an index.代码中的 'j' 是字符串中的一个字符,而不是索引。 Try this:尝试这个:

for (auto character : S)
{
  if (even.length() > odd.length())
  {
    odd.push_back(character);
  }
  else
  {
    even.push_back(character);
  }
}

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

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