reverse()的实现字符串反转和模板reverse的实现
//reverse()的实现 #include <stdio.h> #include <string.h> char* reverse(char* s) { int i,j; for (i=0,j=strlen(s)-1; i<j; ++i,--j) { s[i] = s[i]^s[j]; s[j] = s[i]^s[j]; s[i] = s[i]^s[j]; } return s; } char* reverse2(char* s) { char* start = s; char* end = s+strlen(s)-1; while (start<end) { *start = *start^*end; *end = *start^*end; *start = *start^*end; start++; end--; } return s; } int main() { char str[]="abcdefghijklmnopqrstuvwxyz"; printf("%s\n", str); printf("%s\n", reverse(str)); printf("%s\n", reverse2(str)); return 0; }
//reverse()函数模板的实现 #include <iostream> #include <cstring> using namespace std; template <class BidirectionalIterator> void reverse ( BidirectionalIterator first, BidirectionalIterator last) { while ((first!=last)&&(first!=--last)) { *first = *first^*last; *last = *first^*last; *first = *first^*last; ++first; } } template <class BidirectionalIterator> BidirectionalIterator reverse2(BidirectionalIterator first, BidirectionalIterator last) { BidirectionalIterator begin = first; while ((first!=last)&&(first!=--last)) { *first = *first^*last; *last = *first^*last; *first = *first^*last; ++first; } return begin; } int main() { char str[]="abcdefghijklmnopqrstuvwxyz"; cout << str << endl; reverse(str,str+strlen(str)); cout << str << endl; cout << reverse2(str,str+strlen(str)) << endl; return 0; }
作者:涵曦(www.hanxi.cc)
出处:hanxi.cnblogs.com
GitHub:github.com/hanxi
Email:im.hanxi@gmail.com
文章版权归本人所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
《 Skynet 游戏服务器开发实战》
-
学习地址:
-
优惠推荐码:
2CZ2UA5u
-
可以先免费试学前 2 章内容