Solution: Reverse a String¶
Naive¶
#include <string>
#include <iostream>
using namespace std;
int main()
{
string s;
cin >> s;
string reversed_s;
for (int i=s.size()-1; i>=0; i--)
reversed_s += s[i];
cout << reversed_s << endl;
return 0;
}
Using std::reverse<>
¶
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
string s;
cin >> s;
std::reverse(s.begin(), s.end());
cout << s << endl;
return 0;
}
Using std::reverse_copy<>
¶
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
string s("abc");
string reversed_s(s.size(), '*');
std::reverse_copy(s.cbegin(), s.cend(), reversed_s.begin());
cout << reversed_s << endl;
return 0;
}