c++基础:8.6_STL:类型萃取

1.萃取技术

如何把数组和容器统一起来;
数组:指针;
容器:迭代器

1.1 功能

类型萃取:在STL中用到的比较多,用于判断一个变量是否为POD类型.简述来说可以用来判断出某个变量是内置类型还是自定义类型.通过类型萃取,萃取到变量类型,对不同变量进行不同处理,可以提升程序效率.

1.2 应用场景

比如我们实现顺序表,在对顺序表进行扩容时,就靠重新开辟内存、拷贝对象.

拷贝对象时,就有两种情况:一种是类型,比如int char…;还有一种是自定义类型,Data类、String类.
对于内置类型,我们可以通过memset,来进行赋值.(扩展,浅拷贝相关的类也可以通过memset赋值)

而对于自定义类型,大多数深拷贝的对象来说,我们必须通过调用赋值语句来赋值.

因此,我们通常在拷贝对象时,为了不出现错误,都用赋值语句来赋值.

而我们如果有一种方法/机制可以判断POD类型或者非POD类型.

对于POD类型用memset函数,对于非POD用赋值,这样就能提高程序的效率
实现

1.3 实质

类型萃取,在技术层面,就是利用了模板的特化.

(***) 2.实现:begin(),end()函数

(1)c++11之前的遍历

  list<int> li = {1,2,3,4,5};
    for_each(li.begin(),li.end(),[](int n){cout << n <<" ";});
    cout << endl;
    //(1)c++11之前的遍历
    int arr[] = {1,2,3,4,5};
    for_each(arr,arr+5,[](int n){cout << n <<" ";});
    cout << endl;

(2)begin() / end() C++11

  for_each(miniSTL::begin(vec),miniSTL::end(vec),[](int n){cout << n <<",";});
    cout << endl;
    for_each(miniSTL::begin(s),miniSTL::end(s),[](int n){cout << n <<",";});
    cout << endl;

(3)begin(),end()函数的实现
//(3.1)begin(),迭代器的实现

namespace miniSTL{
template<typename T>
typename T::iterator begin(T& c){
    return c.begin();
}

(3.2)end(),迭代器的实现

template<typename T>
typename T::iterator end(T& c){
    return c.end();
}

偏特化
(3.3)begin(),指针的实现

template<typename T,size_t N>
T* begin(T (&arr)[N]){
    return arr;
}

(3.4)end(),指针的实现

template<typename T,size_t N>
T* end(T (&arr)[N]){
    return arr+N;
}

(4.1)迭代器的调用

  cout << endl;
for_each(miniSTL::begin(li),miniSTL::end(li),[](int n){cout << n <<",";});//4.1迭代器的调用
    cout << endl;

(4.2)指针的调用

   for_each(miniSTL::begin(arr),miniSTL::end(arr),[](int n){cout << n <<",";});//4.2指针的调用

( 5.1) 获取首尾元素的模板函数(value_type:数据类型)

template<typename T>
typename T::value_type front(T& c){
    return *c.begin();
}

( 5.2) 获取尾元素的模板函数

template<typename T>
typename T::value_type back(T& c){
    typename T::iterator e = c.end();
    --e;
    return *e;
    // return *c.rbegin(); 作用相同;
}

(5.3)偏特化(数组的首尾)

template<typename T,size_t N>
T front(T (&arr)[N]){
    return arr[0];
}

template<typename T,size_t N>
T back(T (&arr)[N]){
    return arr[N-1];
}

(6)引用作为参数的时候,可以用const和不带const

(源代码见001_begin_end.cpp)

#include <vector>
#include <list>
#include <set>
#include <algorithm>
#include <iostream>
using namespace std;
//(3)begin(),end()函数的实现
//(3.1)begin(),迭代器的实现
namespace miniSTL{
template<typename T>
typename T::iterator begin(T& c){
    return c.begin();
}
//(3.2)end(),迭代器的实现
template<typename T>
typename T::iterator end(T& c){
    return c.end();
}
// 偏特化
//(3.3)begin(),指针的实现
template<typename T,size_t N>
T* begin(T (&arr)[N]){
    return arr;
}
//(3.4)end(),指针的实现
template<typename T,size_t N>
T* end(T (&arr)[N]){
    return arr+N;
}

}
// 5.1 获取首尾元素的模板函数(value_type:数据类型)
template<typename T>
typename T::value_type front(T& c){
    return *c.begin();
}

// 5.2 获取尾元素的模板函数
template<typename T>
typename T::value_type back(T& c){
    typename T::iterator e = c.end();
    --e;
    return *e;
    // return *c.rbegin(); 作用相同;
}
// 5.3偏特化(数组的首尾)
//(6)引用作为参数的时候,可以用const和不带const
template<typename T,size_t N>
T front(T (&arr)[N]){
    return arr[0];
}

template<typename T,size_t N>
T back(T (&arr)[N]){
    return arr[N-1];
}

int main(){
    vector<int> vec = {1,2,3,4,5};
    for_each(vec.begin(),vec.end(),[](int n){cout << n <<" ";});
    cout << endl;

    set<int> s = {1,2,3,4,5};
    for_each(s.begin(),s.end(),[](int n){cout << n <<" ";});
    cout << endl;
     //(1)c++11之前的遍历
    list<int> li = {1,2,3,4,5};
    for_each(li.begin(),li.end(),[](int n){cout << n <<" ";});
    cout << endl;
    //(1)c++11之前的遍历
    int arr[] = {1,2,3,4,5};
    for_each(arr,arr+5,[](int n){cout << n <<" ";});
    cout << endl;

    // (2)begin() / end() C++11
    for_each(miniSTL::begin(vec),miniSTL::end(vec),[](int n){cout << n <<",";});
    cout << endl;
    for_each(miniSTL::begin(s),miniSTL::end(s),[](int n){cout << n <<",";});
    cout << endl;
    for_each(miniSTL::begin(li),miniSTL::end(li),[](int n){cout << n <<",";});//4.1迭代器的调用
    cout << endl;
    for_each(miniSTL::begin(arr),miniSTL::end(arr),[](int n){cout << n <<",";});//4.2指针的调用
    cout << endl;
    cout << front(vec) << "," << back(vec) << endl;
    cout << front(li) << "," << back(li) << endl;
    cout << front(s) << "," << back(s) << endl;
    cout << front(arr) << "," << back(arr) << endl;
}

(***) 3.typename的作用

(1)类里面的静态成员变量和类内部类型的访问方式是一样的 类名::XXXX.在非模板里面可以直接使用,不需要加上关键字typename。

Simple::Static;
    Simple::Nest n;// (2.3)在非模板里面可以直接使用,不需要加上关键字typename。
    // (1)类里面的静态成员变量和类内部类型的访问方式是一样的 类名::XXXX

(2.1)模板认为类::XXXX只是在访问类的静态成员变量,而不是使用嵌套类定义对象

T::Static; //(2.1)模板认为类::XXXX只是在访问类的静态成员变量,而不是使用嵌套类定义对象

(2.2)如果在模板中使用类里面定义的类型,必须在前面加上关键字typename,提前说明这是一个类型。

typename T::Nest n; // (2.2)如果在模板中使用类里面定义的类型,必须在前面加上关键字typename,提前说明这是一个类型。

(2.3)在非模板里面可以直接使用,不需要加上关键字typename。

Simple::Nest n;// (2.3)在非模板里面可以直接使用,不需要加上关键字typename。

(3)typename是有什么作用?
(3.1)s声明模板的时候,定义模板参数;
(3.2)模板里面传进来类的嵌套类型,声明使用的是类的嵌套类型;

(4)避免的方式2:类型重命名也可以避免

typedef int Number;// (4)类型重命名也可以避免
 typename T::Number num;

(5)尽量不要把typename改成class类型,可能不是类,从而出错;

(完整代码见002_typename.cpp)

#include <iostream>
using namespace std;

class Simple{
public:
    static int Static;
    class Nest{};
    typedef int Number;// (4)类型重命名也可以避免
};
int Simple::Static = 0;
template<typename T>
void Func(T& s){
    T::Static; //(2.1)模板认为类::XXXX只是在访问类的静态成员变量,而不是使用嵌套类定义对象
    typename T::Nest n; // (2.2)如果在模板中使用类里面定义的类型,必须在前面加上关键字typename,提前说明这是一个类型。
    // (3)typename是有什么作用?
    //(3.1)s声明模板的时候,定义模板参数;
    //(3.2)模板里面传进来类的嵌套类型,声明使用的是类的嵌套类型;
    typename T::Number num;
}

int main(){
    Simple::Static;
    Simple::Nest n;// (2.3)在非模板里面可以直接使用,不需要加上关键字typename。
    // (1)类里面的静态成员变量和类内部类型的访问方式是一样的 类名::XXXX
    Simple::Number num;
    Simple s;
    Func(s);
}

(***) 4.将mini:vector,list和begin(),end()结合起来

(完整代码见003_combine)

具体做法:
(1)将day11_vector:: 里面的013_iterator.cpp
和day12_list::里面的006_list.cpp改为头文件;
即:将using namespace xxx 声明和main()函数部分进行删除;
vector.h list.h

(2)(main.cpp)将vector,list的数组初始化方式改为for循环进行赋值;c++11之前不允许,所以需要用for循环,不支持向量转化数组的原因;

vector<int> vec;// = {1,2,3,4,5};(2)c++11之前不允许,所以需要用for循环,不支持向量转化数组的原因;
    for(int i=1;i<6;++i) vec.push_back(i);

(3)value_type没有定义,需要在头文件的public里面进行重命名定义;

public:
    typedef T  value_type; //(3)值类型
    typedef T* pointer;
    typedef T& referance;
    typedef const T& const_referance;
    typedef size_t size_type;

(4)注意list.h里面对于–运算符初始值为空的修改

iterator operator--(){
            if(NULL == p) p = tail;
            else p = p->prev;
            return *this;
        }
        iterator operator--(int){
            iterator tmp(*this);
            if(NULL == p) p = tail;
            else p=p->prev;
            return tmp;
        }

(5)测试函数为001_begin_end.cpp的适当修改
(完整代码)

vector.h

#ifndef __VECTOR_H_
#define __VECTOR_H_
#include <iostream>  //(1)引进头文件

namespace miniSTL{
template<typename T>
class vector{
    T* _data;
    size_t _size;// 元素个数
    size_t _capacity;// 容量
public:
    typedef T value_type;  //(3)value_type的重命名;

    vector():_data(NULL),_size(0),_capacity(0){}
    ~vector(){delete [] _data;}
    // 拷贝构造函数
    // 赋值运算符重载函数
    void push_back(const T& val){
        ++_size;
        if(NULL == _data){
            ++_capacity;
            _data = new T[_capacity];
        }else{
            if(_size>_capacity){ // 扩容
                _capacity*=2;
                T* temp = new T[_capacity];
                for(int i=0;i<_size-1;++i){
                    temp[i] = _data[i];
                }
                delete [] _data;
                _data = temp;
            }
        }
        _data[_size-1] = val;
    }
    int size()const{return _size;}
    int capacity()const{return _capacity;}
    T& operator[](int index){
        return _data[index];
    }
    const T& operator[](int index)const{
        return _data[index];
    }

    // 嵌套类:类中定义的类
    class iterator{
        T* _p;
    public:
        iterator(T* p):_p(p){}
        T& operator*(){return *_p;}
        T* operator->(){return _p;}
        //iterator operator++(){
        //    ++_p;
        //    return *this;
        //}
        bool operator==(const iterator& it)const{
            return _p == it._p;
        }
        bool operator!=(const iterator& it)const{
            return _p != it._p;
            // return !(*this == it);
        }
        // 所有操作符除了前缀后缀还有复合赋值+= -= *=之外,不会改变原来下变量值
        iterator operator+(int n)const{
            return iterator(_p+n);
        }
        iterator operator-(int n)const{
            return iterator(_p-n);
        }
        iterator operator++(){
            return iterator(++_p);
        }
        iterator operator++(int){
            iterator tmp(_p);
            ++_p;
            return tmp;
        }
        iterator operator--(){
            return iterator(--_p);
        }
        iterator operator--(int){
            // iterator tmp(_p);
            iterator tmp(*this);
            --_p;
            return tmp;
        }
    };

    iterator begin(){
        return iterator(_data);
    }
    iterator end(){
        return iterator(_data+_size);
    }
};
}
#endif //__VECTOR_H_

list.h

#ifndef __LIST_H_
#define __LIST_H_
#include <iostream>  //(1)引进头文件

namespace miniSTL{
template<typename T>
class list{
public:
    typedef T  value_type; //(3)值类型
    typedef T* pointer;
    typedef T& referance;
    typedef const T& const_referance;
    typedef size_t size_type;
private:
    struct Node{
        value_type val;
        Node* prev;
        Node* next;
        Node(const_referance val):val(val),prev(NULL),next(NULL){}
    };
    Node* head,*tail;
    size_t _size;
public:


    list():head(NULL),tail(NULL),_size(0){
        head = tail = new Node(value_type());// 头节点
    }
    // 拷贝构造/赋值运算符重载函数
    ~list(){
        while(NULL != head){
            Node* next = head->next;
            delete head;
            head = next;
        }
        head = tail = NULL;
        _size = 0;
    }
    void push_back(const_referance val){
        ++_size;
        Node* node = new Node(val);
        // if(NULL == head){
        //    head = tail = node;
        // }else{
            tail->next = node;
            node->prev = tail;
            tail = node;
        //}
    }

    void push_front(const_referance val){
        ++_size;
        Node* node = new Node(val);
        if(head == tail){
            node->prev = head;
            head->next = node;
            tail = node;
        }else{
            node->prev = head;
            node->next = head->next;
            head->next->prev = node;
            head->next = node;
        }
    }
    void pop_back(){
        if(0==_size) return;
        --_size;
        Node* prev = tail->prev;
        prev->next = NULL;
        delete tail;
        tail = prev;
    }
    void pop_front(){
        if(0==_size) return;
        --_size;
        Node* next = head->next;
        head->next = next->next;
        if(NULL!=next->next) next->next->prev = head;
        delete next;
        if(NULL==head->next) tail=head;
    }

    size_t size()const{
        return _size;
    }
    referance operator[](int index){
        // if(index<0 || index >=_size) throw exception(string("invalid index"));
        int count = 0;
        Node* p = head->next;// 头节点的next是下标为0的元素
        while(NULL != p){
            if(count++ == index) break;
            p = p->next;
        }
        return p->val;
    }

    class iterator{
        Node* p;
        Node* head;
        Node* tail;
    public:
        iterator(Node* p,Node* head,Node* tail):p(p),head(head),tail(tail){}
        T& operator*(){return p->val;}
        T* operator->(){return &(p->val);}
        iterator operator++(){
            p=p->next;
            return *this;
        }
        iterator operator++(int){
            iterator tmp(*this);
            p=p->next;
            return tmp;
        }
        iterator operator--(){
            if(NULL == p) p = tail;
            else p = p->prev;
            return *this;
        }
        iterator operator--(int){
            iterator tmp(*this);
            if(NULL == p) p = tail;
            else p=p->prev;
            return tmp;
        }

        bool operator==(const iterator& it)const{
            return p == it.p;
        }
        bool operator!=(const iterator& it)const{
            return p != it.p;
        }
    };

    iterator begin(){return iterator(head->next,head,tail);} // 头节点的next是下标为0的元素
    iterator end(){return iterator(NULL,head,tail);}
};

template <typename IT,typename FUNC>
void for_each(IT first,IT last,FUNC func){
    while(first!=last){
        func(*first++);
    }
}

template <typename IT,typename VAL>
VAL accumulate(IT first,IT last,VAL val){
    while(first!=last){
        val+=*first++;
    }
    return val;
}

}
#endif //__LIST_H_

main.cpp


#include "vector.h"
#include "list.h"
#include <iostream>
using namespace std;
namespace miniSTL{
template<typename T>
typename T::iterator begin(T& c){
    return c.begin();
}

template<typename T>
typename T::iterator end(T& c){
    return c.end();
}
// 偏特化
template<typename T,size_t N>
T* begin(T (&arr)[N]){
    return arr;
}

template<typename T,size_t N>
T* end(T (&arr)[N]){
    return arr+N;
}

}
// 获取首尾元素的模板函数
template<typename T>
typename T::value_type front(T& c){
    return *c.begin();
}

template<typename T>
typename T::value_type back(T& c){
    typename T::iterator e = c.end();
    --e;
    return *e;
    // return *c.rbegin();
}
// 偏特化
template<typename T,size_t N>
T front(T (&arr)[N]){
    return arr[0];
}

template<typename T,size_t N>
T back(T (&arr)[N]){
    return arr[N-1];
}

using namespace miniSTL;

int main(){
    vector<int> vec;// = {1,2,3,4,5};(2)c++11之前不允许,所以需要用for循环,不支持向量转化数组的原因;
    for(int i=1;i<6;++i) vec.push_back(i);
    for_each(vec.begin(),vec.end(),[](int n){cout << n <<" ";});
    cout << endl;

    list<int> li; //= {1,2,3,4,5};
    for(int i=1;i<6;++i) li.push_back(i);
    for_each(li.begin(),li.end(),[](int n){cout << n <<" ";});
    cout << endl;

    int arr[] = {1,2,3,4,5};
    for_each(arr,arr+5,[](int n){cout << n <<" ";});
    cout << endl;

    // begin() / end() C++11
    for_each(miniSTL::begin(vec),miniSTL::end(vec),[](int n){cout << n <<",";});
    cout << endl;
    for_each(miniSTL::begin(li),miniSTL::end(li),[](int n){cout << n <<",";});
    cout << endl;
    for_each(miniSTL::begin(arr),miniSTL::end(arr),[](int n){cout << n <<",";});
    cout << endl;


    cout << front(vec) << "," << back(vec) << endl;
    cout << front(li) << "," << back(li) << endl;
    cout << front(arr) << "," << back(arr) << endl;
}

(*******)5.c++实战中的vector

在这里插入图片描述
(1)基础变量的转化

/*
    pointer   _data;     // 地址
    size_type _size;     // 元素个数
    size_type _capacity; // 容量大小
    */
    //(1)基础变量的转化
    pointer _start; // _start == _data
    pointer _finish; // _size == _finish - _start;
    pointer _endOfStorage; // _capacity == _endOfStorage - _start

(2.) 尾插元素
(2.1)push第一个元素的做法;

void push_back(const_reference val){  //(2.1)push第一个元素的做法;
        if(NULL == _start){
            _start = new value_type[1];
            _finish = _endOfStorage =  _start+1;
            _start[0] = val;
            return;
        }

2.2拷贝其他元素
(2.2.1)扩容

 int last = size();
        if( _finish==_endOfStorage){         //(2.2)push()其他元素的做法;
            int new_capacity = capacity()*2; //(2.2.1)扩容
                pointer tmp = new value_type[new_capacity];

(2.2.2)拷贝数据

 for(int i=0;i<last;++i){
            tmp[i] = _start[i];
        }
        delete [] _start;
        _start = tmp;
        _endOfStorage = _start+new_capacity;  //(2.2.2)拷贝数据
    }
   (2.2.3)拷贝最后一个数据
 _start[last] = val;
        _finish = _start+last+1;  //(2.2.3)拷贝最后一个数据
    }

(完整代码见004_stardard)
vector.h

#ifndef __VECTOR_H
#define __VECTOR_H

template<typename T>
class vector{
public:
    typedef T value_type;
    typedef T* pointer;
    typedef T& reference;
    typedef const T& const_reference;
    typedef int size_type;

    typedef pointer iterator;
private:
    /*
    pointer   _data;     // 地址
    size_type _size;     // 元素个数
    size_type _capacity; // 容量大小
    */
    //(1)基础变量的转化
    pointer _start; // _start == _data
    pointer _finish; // _size == _finish - _start;
    pointer _endOfStorage; // _capacity == _endOfStorage - _start
public:
    vector():_start(NULL),_finish(NULL),_endOfStorage(NULL){}
    void push_back(const_reference val){  //(2.1)push第一个元素的做法;
        if(NULL == _start){
            _start = new value_type[1];
            _finish = _endOfStorage =  _start+1;
            _start[0] = val;
            return;
        }
        int last = size();
        if( _finish==_endOfStorage){         //(2.2)push()其他元素的做法;
            int new_capacity = capacity()*2; //(2.2.1)扩容
            pointer tmp = new value_type[new_capacity];
            for(int i=0;i<last;++i){
                tmp[i] = _start[i];
            }
            delete [] _start;
            _start = tmp;
            _endOfStorage = _start+new_capacity;  //(2.2.2)拷贝数据
        }
        _start[last] = val;
        _finish = _start+last+1;  //(2.2.3)拷贝最后一个数据
    }
    
    //(3)注意指针的操作
    size_type size()const{return _finish-_start;}
    size_type capacity()const{return _endOfStorage-_start;}
    reference operator[](int index){ return _start[index];}
    const_reference operator[](int index)const{ return _start[index];}
    // 迭代器
    iterator begin(){return _start;}
    iterator end(){return _finish;}
};


#endif // __VECTOR_H

(main.cpp)

#include <iostream>
#include "vector.h"
using namespace std;

int main(){
    vector<int> vec;
    for(int i=0;i<50;++i){
        vec.push_back(i);
        cout << "size:"<<vec.size()<<",capacity:"<<vec.capacity() << endl;
    }

    for(int i=0;i<vec.size();++i){
        cout << vec[i] << " ";
    }
    cout << endl;

    vector<int>::iterator it = vec.begin();
    while(it != vec.end()){
        cout << *it++ << " ";
    }
    cout << endl;

}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值