Reputation: 1566
Is there an easy way to create a palindrome in C++ given the first half? For example given "abcdef", I want to return "abcdeffedcba", while keeping the input first half unchanged?
I know you could do, but is there a better way to do it in one line? In Java, reverse() returns a value therefore you can do it in one line.
string createPalindrome(string & half)
{
string temp = half;
reverse(temp.begin(), temp.end());
return half + temp;
}
Upvotes: 0
Views: 917
Reputation: 35454
If you want to do this in one line, here is an implementation:
#include <string>
#include <iostream>
std::string createPalindrome(const std::string & half)
{
return half + std::string(half.rbegin(), half.rend());
}
int main()
{
std::cout << createPalindrome("abcdef");
}
Note that this basically taking the string and concatenating it with the reverse of itself.
The half.rbegin()
and half.rend()
are reverse iterators, so the temporary reverse string is constructed using these iterators.
Upvotes: 7
Reputation: 126
It is not necessary to do this in one line. The code you have written is perfectly clean and understandable. If you want to use the reverse method, which I would recommend since it does exactly what you want, you cannot do it in one line anyway.
Upvotes: -1