Search code examples
c++g++mingwstdreverse

Error: 'reverse' was not declared in this scope


I created a program to reverse a sentence:

#include <iostream>
#include <string>   

using namespace std;

int main()
{
    string sentence;
    string reversedSentence;
    int i2 = 0;

    cout << "Type in a sentence..." << endl;
    getline(cin, sentence);

    reversedSentence = sentence;
    reverse(reversedSentence.begin(), reversedSentence.end());

    cout << sentence << endl;
}

But when I try to compile it with MinGW G++, this happens:

SentenceReverser.cpp: In function 'int main()':
SentenceReverser.cpp:16:5: error: 'reverse' was not declared in this scope
   16 |     reverse(reversedSentence.begin(), reversedSentence.end());
      |     ^~~~~~~

I don't know what I've done wrong. Help?


Solution

  • std::reverse() is defined in the algorithm header. Include that:

    #include <algorithm>
    

    Also, avoid using namespace std;.