我必须反转一个字符串,但我的代码没有产生任何输出——C++

I have to reverse a string but my code is not producing any output -- C++

给定一个字符串 S 作为输入。我必须反转给定的字符串。

输入:第一行输入包含一个整数T,表示测试用例的数量。接下来是T个测试用例,每个测试用例的第一行包含一个字符串S.

输出:对应每个测试用例,倒序打印字符串S。

为什么我的代码没有产生任何输出? 我这样做了:

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

int main() {
    int t;
    cin>>t;
    while(t--){
      string s;
      int j=0;
      string res;
      cin>>s;
      int l=s.length();
      for(int i=l-1;i>=0;i--)
      {
         res[j]=s[i];
         j++;
      }
      cout<<res<<endl;
    }
    return 0;
}

输入:

1

极客

输出:

std::string 不会自动调整大小,这就是 res[j]=... 不起作用的原因。

要解决此问题,您可以:

  • res[j]=...替换为res.push_back(...)
  • 预先指定字符串大小,例如将 string res; 替换为 string res(s.size(), '[=17=]');

另请注意,在生产中最好这样做:

string res = s;
std::reverse(s.begin(), s.end());

更新。 正如@Blastfurnace 指出的那样,更好的版本是:

std::string res(s.rbegin(), s.rend());