C++ STL中 容器,迭代器,算法之间的耦合关系
2020-06-06 本文已影响0人
JimmyPan
简单实现了容器forward_list 对应迭代器:foward_list_iterator 以及find和advance算法,主要想搞清楚他们是怎么在一起运行的
//
// Created by jiaming pan on 6/6/20.
//
#ifndef FORWARD_LIST_FORWARD_LIST_H
#define FORWARD_LIST_FORWARD_LIST_H
#include <memory>
#include <iostream>
namespace my{
template <typename T>
struct node{
T val;
struct node * next;
} ;
template <typename T>
struct __forward_list_iterator{
typedef __forward_list_iterator self;
typedef std::forward_iterator_tag iterator_category;
typedef T value_type;
typedef T* pointer;
typedef T& reference;
typedef ptrdiff_t difference_type;
typedef node<T> * node_type;
node_type node_;
explicit __forward_list_iterator(node_type node){
node_ = node;
}
__forward_list_iterator(const self & self_){
node_ = self_.node_;
}
reference operator*() const {
return node_->val;
}
self& operator++() {
node_ = node_->next;
return *this;
}
bool operator ==(const self & comp) const{
return this->node_ == comp.node_;
}
bool operator !=(const self & comp) const{
return this->node_ != comp.node_;
}
self operator++(int) {
self tmp = *this;
++*this;
return tmp;
}
};
template <typename T>
class forward_list {
public:
using Node = node<T>;
forward_list() {
rear_ = new Node;
head_ = rear_;
};
typedef __forward_list_iterator<T> iterator;
void insert_back(T value){
rear_->val = value;
auto tmp = new Node;
rear_->next = tmp;
rear_ = tmp;
}
iterator begin() const {
return iterator(head_);
}
iterator end() const{
return iterator(rear_);
}
private:
Node * head_;
Node * rear_;
};
template <typename iteratorT,typename elementT>
iteratorT find(iteratorT iteratorBegin,iteratorT iteratorEnd,const elementT & target){
for( auto & item = iteratorBegin; item != iteratorEnd; item ++){
if(*item == target) return item;
}
}
template <typename iteratorT,typename distT>
void doAdvance(iteratorT& iter , distT dist,std::forward_iterator_tag){
std::cout << "doAdvance forward_iterator_tag" <<std::endl;
while(dist -- ){
++iter;
}
}
template <typename iteratorT,typename distT>
void doAdvance(iteratorT& iter , distT dist,std::random_access_iterator_tag){
std::cout << "doAdvance random_access_iterator_tag" <<std::endl;
iter += dist;
}
template <typename iteratorT>
struct iterator_traits{
typedef typename iteratorT::iterator_category iterator_category;
};
template <typename iteratorT>
struct iterator_traits<iteratorT *>{
typedef typename std::random_access_iterator_tag iterator_category;
};
template <typename iteratorT>
struct iterator_traits<const iteratorT *>{
typedef typename std::random_access_iterator_tag iterator_category;
};
template <typename iteratorT,typename distT>
void advance(iteratorT& iter , distT dist){
// doAdvance(iter,dist,typename iteratorT::iterator_category());并不能接收普通指针,因为普通指针内没有定义iterator_category
doAdvance(iter,dist,typename iterator_traits<iteratorT>::iterator_category());
}
}
#endif //FORWARD_LIST_FORWARD_LIST_H