深入设模式之:迭代器模式之编写一个兼容STL 算法的Iterator

#include <vector>
#include <algorithm>

class Seat
{
public:
Seat(int no):no_(no) {}
int no_;
};


class Table
{
static const std::size_t BEGIN_SEAT = 1;
static const std::size_t INVALID_SEAT = 0;
static const std::size_t END_SEAT = 9;
public:
Table()
{
seats_.push_back(new Seat(1) );
seats_.push_back(new Seat(2) );
seats_.push_back(new Seat(3) );
seats_.push_back(new Seat(4) );
seats_.push_back(new Seat(5) );
seats_.push_back(new Seat(6) );
seats_.push_back(new Seat(7) );
seats_.push_back(new Seat(8) );
seats_.push_back(new Seat(9) );
}


std::vector<Seat *> seats_;


Seat * get( const int seat )
{
return seats_.at(seat - 1);
}


public:
class Iterator 
{
friend class CycleIterator;
public:
typedef size_t size_type;
typedef ptrdiff_t difference_type;


typedef std::forward_iterator_tag iterator_category;
typedef Seat *        value_type;
typedef Seat **           pointer;
typedef Seat *&         reference;


Iterator(Table * table, const int position):table_(table), position_(position) {}


Iterator(const Iterator & it):table_(it.table_), position_(it.position_) {}


Iterator operator ++()
{
for (++position_; position_ <= Table::END_SEAT;++position_ )
{
//if (table_->get(position_)->visible_ == true)
{
return Iterator(table_, position_);
}
}


position_ = Table::INVALID_SEAT;


return Iterator(table_, Table::INVALID_SEAT);
}


Seat * operator ->()
{
return table_->get(position_);
}


Seat * operator *()
{
return table_->get(position_);
}


bool operator == (const Iterator & it)const
{
return position_ == it.position_;
}


bool operator != (const Iterator & it)const
{
return position_ != it.position_;
}


private:
Table * table_;


int position_;
};


public:
Iterator begin()
{
return Iterator(this, BEGIN_SEAT);
}


Iterator end()
{
return Iterator(this, INVALID_SEAT);
}
};


bool FindNullSeat(Seat *  seat)
{
return seat->no_ == 3;
}


int main(int , char **)
{
Table table;
Table::Iterator seat = std::find_if(table.begin(), table.end(), FindNullSeat);


return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值