fork download
  1. #include <algorithm>
  2. #include <cctype>
  3. #include <string>
  4. #include <iostream>
  5.  
  6. struct CaesarCipher {
  7. std::string alphabet;
  8. int shift;
  9.  
  10. CaesarCipher(std::string alphabet, int sh) : alphabet(alphabet) {
  11. shift = std::abs(sh) % alphabet.length();
  12. if (sh < 0) shift = alphabet.length() - shift;
  13. }
  14.  
  15. //Encrypts one character
  16. char operator() (char c) {
  17. int index = alphabet.find(c);
  18. if (index != std::string::npos)
  19. return alphabet[(index + shift) % alphabet.length()];
  20. else return c;
  21. }
  22. };
  23.  
  24. //Encrypts a container using given alphabet
  25. template <typename InputIterator, typename OutputIterator>
  26. OutputIterator generic_caesar_cipher(
  27. InputIterator src_begin, InputIterator src_end, OutputIterator dest_begin,
  28. std::string alphabet, int shift)
  29. {
  30. return std::transform(src_begin, src_end, dest_begin, CaesarCipher(alphabet, shift));
  31. }
  32.  
  33. //Encrypts a container using the lowercase latin alphabet
  34. template <typename InputIterator, typename OutputIterator>
  35. OutputIterator caesar_cipher(
  36. InputIterator src_begin, InputIterator src_end, OutputIterator dest_begin,
  37. int shift)
  38. {
  39. return generic_caesar_cipher(src_begin, src_end, dest_begin, "abcdefghijklmnopqrstuvwxyz", shift);
  40. }
  41.  
  42. int main() {
  43. std::string s = "wkh txlfn eurzq ira mxpsv ryhu wkh odcb grj";
  44.  
  45. caesar_cipher(s.begin(), s.end(), s.begin(), -3);
  46. std::cout << s << std::endl;
  47. }
Success #stdin #stdout 0s 3020KB
stdin
Standard input is empty
stdout
the quick brown fox jumps over the lazy dog