首先看图
代码:
// test.cpp : 定义控制台应用程序的入口点。
//C++程序设计
//2015-5-4
//STL strandard template libeary
#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
#include <iterator>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
//演示泛型指针和copy函数的例子
double a[] = { 1.1, 4.4, 3.3, 2.2 };
vector<double> va(a, a + 4); //初始化并定义va
typedef vector<double>::iterator vi;
vi first = va.begin(); //自定义一个正向泛型指针first并指向va的首元素
for (first; first < va.end(); first++) //正向输出va
cout << *first << " ";
cout << endl;
//循环逆向输出va
for (--first; first>va.begin(); first--) //不做va.begin()-1
{
cout << *first << " ";
if (first == va.begin()+1) //当指针到达being()后一个地址时,同时输出begin()地址上的值
cout << *(first-1) << " ";
}
cout << endl;
copy(va.begin(), va.end(), ostream_iterator<double>(cout, " ")); //整体正向输出va
cout << endl;
typedef vector<double>::reverse_iterator vri;
vri last = va.rbegin();
//使用逆向指针循环从尾到首输出va
for (last; last<va.rend(); last++)
{
cout << *last << " ";
}
cout << endl;
//使用逆向指针循环从首到尾输出va
for (--last; last>va.rbegin(); last--)
{
cout << *last << " " ;
if (last == va.rbegin() + 1) //当指针到达rbeing()前一个地址时,同时输出rbegin()地址上的值
cout << *(last - 1) << " ";
}
cout << endl;
copy(va.rbegin(), va.rend(), ostream_iterator<double>(cout, " ")); //整体从尾到首输出va
cout << endl;
return 0;
//C++程序设计
//2015-5-4
//STL strandard template libeary
#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
#include <iterator>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
//演示泛型指针和copy函数的例子
double a[] = { 1.1, 4.4, 3.3, 2.2 };
vector<double> va(a, a + 4); //初始化并定义va
typedef vector<double>::iterator vi;
vi first = va.begin(); //自定义一个正向泛型指针first并指向va的首元素
for (first; first < va.end(); first++) //正向输出va
cout << *first << " ";
cout << endl;
//循环逆向输出va
for (--first; first>va.begin(); first--) //不做va.begin()-1
{
cout << *first << " ";
if (first == va.begin()+1) //当指针到达being()后一个地址时,同时输出begin()地址上的值
cout << *(first-1) << " ";
}
cout << endl;
copy(va.begin(), va.end(), ostream_iterator<double>(cout, " ")); //整体正向输出va
cout << endl;
typedef vector<double>::reverse_iterator vri;
vri last = va.rbegin();
//使用逆向指针循环从尾到首输出va
for (last; last<va.rend(); last++)
{
cout << *last << " ";
}
cout << endl;
//使用逆向指针循环从首到尾输出va
for (--last; last>va.rbegin(); last--)
{
cout << *last << " " ;
if (last == va.rbegin() + 1) //当指针到达rbeing()前一个地址时,同时输出rbegin()地址上的值
cout << *(last - 1) << " ";
}
cout << endl;
copy(va.rbegin(), va.rend(), ostream_iterator<double>(cout, " ")); //整体从尾到首输出va
cout << endl;
return 0;
}
不能将for (--first; first>va.begin(); first--) 或 for (--last; last>va.rbegin(); last--) 中的
va.begion()-1 或 va.rbegin()-1,原因是fisrt指针,它们的在数组中的作用范围各自是[begion,end)与(rend,rbegion]
就是说:正向泛型指针逆向循环时,a.begin以外的范围。所以代码中-1会心指针继续做first--,到此报错Expreeeion:vector iterator + offset out of range。
逆向泛型指针同理。