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;
}

image

posted @ 2012-10-16 08:26  涵曦  阅读(3405)  评论(1编辑  收藏  举报