3

我的编译器不喜欢以下代码的几件事。非常感谢任何帮助。由于我是一名编程n00b,请随意批评我。我知道你们可能很严厉。

// Method 2, the additive swap, explained inside. 
void strrev2(std::string& str) { 
    unsigned len = str.size(); 
    for (unsigned i = 0, j = len - 1; i < j; i++, j--) { 
        short a = (int)str[i]; // a is the ASCII value of the i-th character of the string
        short b = (int)str[j]; // b is the ASCII value of the j-th character of the string

        //             Current value of a        Current value of b
        a = a + b; //      a + b                         b        
        b = a - b; //      a + b                         a
        a = a - b; //        b                           a
    }

    str[i] = (char)a;
    str[j] = (char)b;
} 
4

1 回答 1

5

i,j,a,b在循环外不可用for,但您正试图在for循环外访问它们。您可以考虑str[i] = (char)a;在循环内移动:

for (unsigned i = 0, j = len - 1; i < j; i++, j--) { 
  ....
  ...
  str[i] = (char)a;
  str[j] = (char)b;   
}
于 2013-09-07T04:35:12.253 回答