-4

I am trying to reverse a string (c++, compiling with g++). Isn't string considered a container for the algorithm functions?

This is the code:

#include <string>
#include <algorithm> 


using namespace std;


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

    return 0;
}

Thanks

Hana
  • 535
  • 2
  • 7
  • 17
  • 2
    did you mean std::reverse? – UKMonkey Oct 11 '17 at 13:55
  • 5
    You should consult the [reference](http://en.cppreference.com/w/cpp/algorithm/reverse) when you use something new and it doesn't work to make sure you are using it correctly. – NathanOliver Oct 11 '17 at 13:56
  • yes, `string` is a container, but no `string` has no `reverse` you probably meant `std::reverse(str.begin(),str.end())`. And your mixing of reverese and forward iterators is weird. I avoid reverse iterators whenever I can, because I always get it wrong, but this looks wrong too – 463035818_is_not_an_ai Oct 11 '17 at 13:56
  • I think you want to use `std::reverse`, the [STD function](http://en.cppreference.com/w/cpp/algorithm/reverse) in the `algorithm` header – HatsuPointerKun Oct 11 '17 at 13:57
  • 1
    Possible duplicate of [How do you reverse a string in place in C or C++?](https://stackoverflow.com/questions/198199/how-do-you-reverse-a-string-in-place-in-c-or-c) – izlin Oct 11 '17 at 14:00
  • 2
    Your error demonstrates why algorithms exist. Note that `std::reverse` works with any sequence container. That's why there is no `std::string::reverse`, `std::array::reverse`, `std::vector::reverse`, etc. The same `std::reverse` works for all of them. – PaulMcKenzie Oct 11 '17 at 14:01
  • You’re right that `std::string` does not have a member function named `reverse`. No containers do. RTFM. – Pete Becker Oct 11 '17 at 14:13

2 Answers2

4

The std::string class template does not have a member function called reverse. There is a std::reverse function located in the <algorithm> header. You probably want to use it in a following manner:

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

Note the use of str.end() in place of your str.rbegin(). You can also define a new string and use the string constructor overload that accepts reverse iterators:

#include <string>
int main() {
    std::string str = "hello";
    std::string reversestr(str.rbegin(), str.rend());
}
Ron
  • 14,674
  • 4
  • 34
  • 47
0

std::string has no method reverse. But std::reverse exists:

#include <string>
#include <algorithm>
#include <iostream>

int main()
{
    std::string str = "hello";
    std::reverse(str.begin(), str.end());
    std::cout << str << "\n"; // prints "olleh"
}
YSC
  • 38,212
  • 9
  • 96
  • 149