Skip to content

Instantly share code, notes, and snippets.

@zyxar
Created October 21, 2012 17:15
Show Gist options
  • Save zyxar/3927663 to your computer and use it in GitHub Desktop.
Save zyxar/3927663 to your computer and use it in GitHub Desktop.
misc. c plus plus exercises
#include <iostream>
#include <string>
#define swap(a, b) { \
a ^= b; \
b ^= a; \
a ^= b;}
std::string& reverse(std::string& str, int start, int end) {
if (end == start) return str;
int i = start, j = end;
while (i < j) {
swap(str[i], str[j]);
++i;
--j;
}
return str;
}
std::string& shift_n(std::string& str, int n) {
int len = str.length();
n = n % len;
reverse(str, 0, n-1);
reverse(str, n, len-1);
return reverse(str, 0, len-1);
}
std::string& _shift(std::string& str, int s, int n) {
// std::cout<<"[debug1:] "<<str<<std::endl;
int len = str.length() - s;
n = n % len;
// std::cout<<"[debug2:] "<<s<<" "<<n<<" "<<len<<std::endl;
if (n == 0) return str;
int i = s;
while(i < s + n && i < s + len - n) {
swap(str[i], str[n+i]);
i++;
}
if (n+n >= len) {
n = n+n-len;
}
return _shift(str, i, n);
}
std::string& shift_m(std::string& str, int m) {
return _shift(str, 0, m);
}
std::string& operator<<(std::string& str, int n) {
return _shift(str, 0, n);
}
std::string& operator>>(std::string& str, int n) {
return _shift(str, 0, str.size()-n);
}
int main(int argc, char const *argv[])
{
int n;
if (argc < 2) n = 5;
else n = atoi(argv[1]);
std::string in("abcdefg");
std::cout<<in<<std::endl;
// shift_n(in, 13);
// std::cout<<in<<std::endl;
shift_m(in, n);
std::cout<<in<<std::endl;
std::cout<<(in<<4)<<std::endl<<(in>>2)<<std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment