简体   繁体   English

这个反向字符串代码正确吗?

[英]Is this reverse string code correct?

This code works for me when I run it on my IDE, but it doesn't work on the website that has the exercise. 当我在IDE上运行该代码时,此代码对我有用,但在进行此练习的网站上却不起作用。 I get a segmentation fault. 我遇到了细分错误。 So is this code correct? 那么这段代码正确吗? Did I make a mistake? 我做错了吗?

#include <iostream>
#include <string>
using namespace std;

string FirstReverse(string str) { 
  for (int i = 0, back = str.size()-1; i != back; ++i, --back)
  {
    char c = str[back];
    str[back] = str[i];
    str[i] = c;
  }
  return str; 
}

int main() {
  cout << FirstReverse("hello");
  return 0;
}

Also, what's the best way to do this? 另外,最好的方法是什么?

Your index only needs to reach half of the length, and that way we ensure that the swap between a pair only happens once: 您的索引只需要达到长度的一半,这样我们就可以确保一对之间的交换仅发生一次:

for (int i = 0; i < str.size() / 2 ; i ++)
{
    char c = str[str.size() - 1 - i];
    str[str.size() - 1 - i] = str[i];
    str[i] = c;

} }

If you change the loop condition to "i <= back" then it won't cause segmentation fault. 如果将循环条件更改为“ i <= back”,则不会导致分段错误。 It is because when size-1 is even , i & back will never become equal. 这是因为当size-1为偶数时,i&back将永远不会相等。 Thus loop will keep on going without breaking & attempt to access string member outside the string. 因此,循环将继续进行而不会中断&尝试访问字符串外部的字符串成员。

只需将您的条件从!=更改为<=解决。

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

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