language: C++11 (gcc-4.7.2)
date: 145 days 4 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
40
41
42
43
44
45
46
47
#include <algorithm>
#include <cctype>
#include <string>
#include <iostream>
 
struct CaesarCipher {
    std::string alphabet;
    int shift;
    
    CaesarCipher(std::string alphabet, int sh) : alphabet(alphabet) {
        shift = std::abs(sh) % alphabet.length();
        if (sh < 0) shift = alphabet.length() - shift;
    }
    
    //Encrypts one character
    char operator() (char c) {
        int index = alphabet.find(c);
        if (index != std::string::npos)
           return alphabet[(index + shift) % alphabet.length()];
        else return c;
    }
};
 
//Encrypts a container using given alphabet
template <typename InputIterator, typename OutputIterator>
OutputIterator generic_caesar_cipher(
    InputIterator src_begin, InputIterator src_end, OutputIterator dest_begin,
    std::string alphabet, int shift)
{
    return std::transform(src_begin, src_end, dest_begin, CaesarCipher(alphabet, shift));
}
 
//Encrypts a container using the lowercase latin alphabet
template <typename InputIterator, typename OutputIterator>
OutputIterator caesar_cipher(
    InputIterator src_begin, InputIterator src_end, OutputIterator dest_begin,
    int shift)
{
    return generic_caesar_cipher(src_begin, src_end, dest_begin, "abcdefghijklmnopqrstuvwxyz", shift);
}
 
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;
}