language: C++11 (gcc-4.7.2)
date: 176 days 18 hours ago
link:
visibility: public
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <algorithm>
#include <cctype>
#include <string>
#include <iostream>
 
template <typename InputIterator, typename OutputIterator>
OutputIterator caesar_cipher(InputIterator src_begin, InputIterator src_end, OutputIterator dest_begin, int shift)
{
    const std::string ab("abcdefghijklmnopqrstuvwxyz"); // AlphaBet
    std::string rot_ab(ab); // ROTated AlphaBet
 
    shift %= static_cast<int> (ab.length()); // bring the shift within the length of the alphabet
 
    if (shift < 0)
        std::rotate(rot_ab.rbegin(), rot_ab.rbegin() - shift, rot_ab.rend());
    else
        std::rotate(rot_ab.begin(), rot_ab.begin() + shift, rot_ab.end());
        
    auto rotator = [ab, rot_ab](char c) -> char {
        if (std::isalpha(c))
        {
            if (std::isupper(c))
                return std::toupper(rot_ab.at(ab.find(std::tolower(c))));
 
            return rot_ab.at(ab.find(c));
        }
 
        return c;
    };
 
    return std::transform(src_begin, src_end, dest_begin, rotator);
}
 
int main() {
    std::string s = "Wkh Txlfn Eurzq Ira Mxpsv Ryhu Wkh Odcb Grj";
 
    caesar_cipher(s.begin(), s.end(), s.begin(), -3);
    std::cout << s << std::endl;
}