C++泛型指针的正向与逆向循环读取的改进方法

#include "stdafx.h"
#include <algorithm>
#include <functional>
#include <vector>
#include <iterator> 

using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
    //双向访问的例子
    char st[11] = "abcdefghij";
    vector<char> a(st, st + 10);
    vector<char>::iterator p = a.begin();    //定义正向泛型指针并初始化
    vector<char>::reverse_iterator ps;    //正义逆向泛型指针
    for (p = a.begin(); p != a.end(); ++p)    //正向访问
    {
        cout << *p << " ";
    }
    cout << endl;
    for (p = a.end(); p != a.begin(); --p)    //使用正向泛型指针逆向访问
    {
        cout << *(p - 1) << " ";
    }
    cout << endl;
    for (ps = a.rbegin(); ps != a.rend(); ++ps)    //使用逆向泛型指针正向访问,使用++运算
    {
        cout << *ps << " ";
    }
    cout << endl;
    for (; ps != a.rbegin(); --ps)    //使用逆向泛型指针逆向访问,使用--运算
    {
        cout << *(ps - 1) << " ";
    }
    return 0;
}
posted @ 2015-05-06 11:46  明月忧忧  阅读(504)  评论(0编辑  收藏  举报