/*******************************************************************************
在这里仅仅是为了实现一个索引递增游标,既然是一个STL兼容游标,当然就需要遵守STL
游标规范,这里只使用了前向游标,所以代码中的基类采用了STL的iterator模板,采用了
前向游标标志(std::forward_iterator_tag),因为是一个索引游标,所以游标所指向的
元素就是size_t类型,当然也可以是其它类型,这根据需要而定。
需要注意的是想要自定义一个STL兼容的前向游标类必须遵守下述规范:
------------------------------------------------------
a:解引用操作符(operator*)
b:前递增操作符(operator++())
c:后递增操作符(operator++(int))
d:相等操作符(operator==)
e:不等操作符(operator!=)
------------------------------------------------------
STL中的游标类:
------------------------------------------------------
1.输入游标类(std::input_iterator_tag)
2.输出游标类(std::output_iterator_tag)
3.前向游标类(std::forward_iterator_tag)
3.双向游标类(std::bidirectional_iterator_tag)
4.随机访问游标类(std::random_access_iterator_tag)
------------------------------------------------------
就必须遵守相应的规范定义出相应的操作符,具体的这些规范这里不一一列出,如果想知道
相应的具体规范可以参见STL标准。网上有很多的,随便一搜一大堆,英文中文都有的。
*******************************************************************************/
#include <iostream>//当然是输入输出啦:)
#include <algorithm>//使用了std::copy算法
#include <iterator>//使用了std::iterator模板
//自定义一个循环游标类
class loop_iterator:public std::iterator<std::forward_iterator_tag,size_t>
{
public:
loop_iterator(size_t const&i):_i(i){}
size_t& operator*(){return _i;}//a:解引用操作符
const size_t& operator++()//b:前递增操作符
{ _i++;return _i; }
const size_t& operator++(int)//c:后递增操作符
{ _i++;return _i; }
bool operator==(const loop_iterator& other) const//d:相等操作符
{ return _i == other._i; }
bool operator!=(const loop_iterator& other) const//e:不等操作符
{ return _i != other._i; }
private:
size_t _i;
};
//上面的没有注释的部分是定义STL兼容游标类不必要的,这里用来保存索引值,当然还
//可以根据具体的需要添加许许多多额外的变量,这就看你的发挥了。
//下面的测试程序一目了然,不需要过多解释。如果你不明白什么意思,就需要进一步的
//熟悉STL了:)
int main()
{
loop_iterator begin(0),end(10);//定义一个从0到9的索引序列[0,10)
std::copy(begin,end,std::ostream_iterator<int>(std::cout," "));
return 0;
}
//运行结果如下:
/*******************************************************************************
0 1 2 3 4 5 6 7 8 9
*******************************************************************************/
自定义STL游标实现虚拟容器(1)
最新推荐文章于 2022-07-25 12:07:59 发布