字符串没有名为 'reverse' 的成员

string has no member named 'reverse'

本文关键字:reverse 成员 字符串      更新时间:2023-10-16

我正在尝试反转字符串(c ++,用g ++编译)。字符串不被视为算法函数的容器吗?

这是代码:

#include <string>
#include <algorithm> 

using namespace std;

int main()
{
    string str = "hello";
    str.reverse(str.begin(), str.rbegin());
    return 0;
}

谢谢

std::string 类模板没有名为 reverse 的成员函数。有一个 std::reverse 函数位于 <algorithm> 标头中。您可能希望通过以下方式使用它:

#include <string>
#include <algorithm> 
int main() {
    std::string str = "hello";
    std::reverse(str.begin(), str.end());
}

请注意使用 str.end() 代替您的str.rbegin()。您还可以定义一个新字符串,并使用接受反向迭代器的字符串构造函数重载:

#include <string>
int main() {
    std::string str = "hello";
    std::string reversestr(str.rbegin(), str.rend());
}

std::string没有方法reverse。但std::reverse存在:

#include <string>
#include <algorithm>
#include <iostream>
int main()
{
    std::string str = "hello";
    std::reverse(str.begin(), str.end());
    std::cout << str << "n"; // prints "olleh"
}