C++: Check if the String is Palindrome

1. #include <iostream>
2. #include <algorithm>
3. #include <string>

4. bool is_palindrom(const std::string& str)
5. {
6.    std::string temp(str);
7.    std::transform(temp.begin(), temp.end(), temp.begin(), ::tolower);
8.    return temp == std::string(temp.rbegin(), temp.rend());
9. }

10. int main()
11. {
12.    std::string str{ "KArak" };
13.    std::cout << is_palindrom(str) << std::endl;
14.    return 0;
15. }

We are not writing using namespace std because it 

forces all includers of that header file to use that namespace, which might result in naming ambiguities that are hard to fix. This practice is called namespace pollution. Instead, always use the fully prefixed names in header files (std::string not string) and save the using declarations for the source files.

In line 7 transform algorithm is used. It applies a function to a range of elements and stores the outcome in new sequence. The function used is tolower which lowers all the capital alphabets.An example of Transform Algorithm 

Popular Posts

Top 10 Web Sites Every Programmer Should Visit Daily

C++: Huffman Coding using STL

What is "namespace" and why do we use it?