【问题标题】:string not reversed [duplicate]字符串未反转[重复]
【发布时间】:2022-01-22 14:26:04
【问题描述】:

这段代码有什么问题?即使我写了 s.reverse(),字符串也没有反转。它显示相同的字符串而不反转?有人可以帮我解决这个问题吗?

#include<iostream>
using namespace std;
int main(){

cout << "Hello world" << endl;;
string s;
cin >> s;
s.reverse();
cout << s;
}

【问题讨论】:

  • reverse 方法需要 2 个参数 - 开始和结束迭代器
  • 是的,谢谢@CS,知道了。

标签: c++ string


【解决方案1】:

当您检查the reference document 时,您会看到 reverse 方法具有以下原型:

void reverse (BidirectionalIterator first, BidirectionalIterator last);

此方法反转[first,last] 范围内元素的顺序。

更新调用std::reverse()的行如下:

#include <algorithm>

std::reverse(s.begin(), s.end());

【讨论】:

    【解决方案2】:

    std::string 没有reverse() 方法,因此调用s.reverse() 甚至不应该编译。

    您需要改用std::reverse() 算法:

    #include <iostream>
    #include <string>
    #include <algorithm>
    
    int main(){
        std::cout << "Hello world" << std::endl;
        std::string s;
        std::cin >> s;
        std::reverse(s.begin(), s.end());
        std::cout << s;
    }
    

    【讨论】:

      猜你喜欢
      • 2017-06-21
      • 2011-09-27
      • 1970-01-01
      • 2015-10-25
      • 2014-06-10
      • 2019-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多