目录
主要知识点:
具体实现代码:
辅助测试函数:仿函数,lambad表达式,算法string类型测试
allocator类
allocator 的标准接口,最重要的就是内存相关的 allocate 和 deallocate;构造相关的 construct 和 destroy。(两者分离)然后就是实现一个简单的配置器,没有内存管理,只是简单的malloc。
- allocate 和 deallocate 负责获取可以用的内存。
- construct调用placement new构造函数,destroy调用相应类型的析构函数 ~T()。
/allocator类(模板)在<memory>中
//分配原始内存和构造对象初始化,与new分配构造同时进行不同
uninitialized_XX(未初始化原始内存函数)
initializer_list c++11新特性:
initializer_list是C++11提供的新类型,定义在头文件<initializer_list>中。
用于表示某种特定类型的值的数组,和vector一样,initializer_list也是一种模板类型。
initializer_list<T> lst;
//默认初始化;T类型元素的空列表
initializer_list<T> lst{a,b,c...};
//lst的元素数量和初始值一样多;lst的元素是对应初始值的副本
lst2(lst)
lst2=lst
//拷贝或赋值一个initializer_list对象不会拷贝列表中的元素;拷贝后,原始列表和副本元素共享
lst.size() //列表中的元素数量
lst.begin() //返回指向lst中首元素的指针
lst.end() //返回指向lst中尾元素下一位置的指针
注意:,initializer_list对象中的元素永远是常量值,我们无法改变initializer_list对象中元素的值。并且,拷贝或赋值一个initializer_list对象不会拷贝列表中的元素,其实只是引用而已,原始列表和副本共享元素。
MyVector类:
#include<iostream>
#include<string>
#include<algorithm>
#include<functional>
#include<memory>
using namespace std;
template<typename T>
class MyVector
{
public:
MyVector() :elements(nullptr), first_free(nullptr), cap(nullptr) {};
MyVector(const MyVector&);
MyVector(const initializer_list<T>&init_list);
//右值表达式&&右值引用常量表达式,不能引用左值,变量等,右值引用短暂,左值引用持久
//移动构造函数,不分配内存,窃取旧内存,被窃取后移后源会被销毁,能运行析构函数
MyVector(MyVector&&s) noexcept:elements(s.elements), first_free(s.first_free), cap(s.cap)//noexcept没有异常必须写
{
s.elements = s.first_free = s.cap = nullptr;
}
MyVector& operator=(MyVector&);
//initializer_list是标准库模板成员,
//initializer_list<int> l1;initializer_list<int> l2={}
//l1(l2) l1 = l2 l1.begin() l1.end() l1.size()
//类似于vector 但是元素永远是常量const不可变
//{}
MyVector& operator=(MyVector&&rhs) noexcept//移动赋值函数
{
//检测自赋值
if (this != &rhs)//取地址
{
free();
elements = rhs.elements;
first_free = rhs.first_free;
cap = rhs.cap;
//移后源置位可析构状态
rhs.elements = rhs.first_free = rhs.cap = nullptr;
}
return *this;
}
//下标运算符一般定义一个正常版一个常量版
T&operator[](size_t n) { return elements[n]; }
const T&operator[](size_t n)const { return elements[n]; }
void push_back(const T&);
void pop_back();
T&front();
T&back();
T*begin() { return elements; }
T*end() { return first_free; }
size_t size() { return first_free - elements; }
size_t capactiy() { return cap - elements; }
~MyVector();
private:
T *elements;
T *first_free;
T *cap;
static allocator<T>alloc;//静态成员声明空间配置器,必须在类外边定义
void chk_n_alloc()
{
if (size() == capactiy())
reallocate();
}
pair<T*, T*> alloc_n_copy(const T*, const T*);
void free();
void reallocate();
};
template<typename T>
allocator<T> MyVector<T>::alloc;
template<typename T>
void MyVector<T>::push_back(const T&str)
{
chk_n_alloc();
alloc.construct(first_free++, str);
}
template<typename T>
void MyVector<T>::pop_back()
{
first_free--;
}
template<typename T>
T& MyVector<T>::front()
{
return *elements;
}
template<typename T>
T&MyVector<T>::back()
{
return *(first_free - 1);
}
template<typename T>
pair<T*, T*> MyVector<T>::alloc_n_copy(const T*b, const T*e)
{
auto data = alloc.allocate(e - b);
auto p = uninitialized_copy(b, e, data);
return { data,p };
}
template<typename T>
void MyVector<T>::free()
{
if (elements)
{
for (auto p = first_free; p != elements;)
alloc.destroy(--p);//析构对象
alloc.deallocate(elements, cap - elements);//释放内存
}
}
template<typename T>
MyVector<T>::MyVector(const MyVector<T>&rhs)
{
auto dest = alloc_n_copy(rhs.elements, rhs.first_free);
elements = dest.first;
first_free = cap = dest.second;
}
template<typename T>
MyVector<T>& MyVector<T>::operator=(MyVector<T>&rhs)
{
auto data = alloc_n_copy(rhs.elements, rhs.first_free);
free();
elements = data.first;
first_free = cap = data.second;
return *this;
}
//花括号赋值:支持可变形参
template<typename T>
MyVector<T>::MyVector(const initializer_list<T>&rhs)
{
auto data = alloc_n_copy(rhs.begin(), rhs.end());
free();
elements = data.first;
first_free = cap = data.second;
}
template<typename T>
void MyVector<T>::reallocate()
{
auto newcapacity = size() ? 2 * size() : 1;//初始size()为1,后面2倍扩容
auto data = alloc.allocate(newcapacity);
auto dest = data;
auto from = elements;
for (size_t i = 0; i < size(); i++)
alloc.construct(dest++, std::move(*from++));//调用move的返回右值引用,值会调用string的移动构造函数,
//调用拷贝构造函数,进行拷贝构造开销大
free();
elements = data;
first_free = dest;
cap = elements + newcapacity;
}
template<typename T>
MyVector<T>::~MyVector()
{
free();
}
辅助测试函数:仿函数,lambad表达式,算法string类型测试
class printString
{
public:
printString(ostream&o = cout, char c = ' ') :os(o), sep(c) {}
void operator()(const string s) { os << s << sep; }
~printString() {}
private://函数对象类 包含表示状态的数据成员用来定制运算符中调操作
ostream&os;
char sep;
};
struct shorting
{
public:
bool operator()(const string str1, const string str2)const
{
return (str1.size() < str2.size());
}
};
测试实例:
void MyVector_opt()
{
MyVector<string> s1;
s1.push_back("You");
cout << "初始size" << endl;
s1.push_back("are");
cout << "2倍扩容口的size" << endl;
s1.push_back("a");
s1.push_back("very");
s1.push_back("nice");
s1.push_back("man");
cout << " the size is " << s1.size() << " the capacity is: " << s1.capactiy() << endl;
for (auto c : s1)
cout << c << " ";
cout << endl;
cout << "头元素" << s1.front() << endl;
//算法调用函数对象 测试算法接口
for_each(s1.begin(), s1.end(), printString(cout, ','));//临时对象
cout << endl;
printString ptrstr(cout, '-');//定义对象
//喊出stable_sort调用每次比较调用shorting的临时对象。对象调用运算符的函数体
stable_sort(s1.begin(), s1.end(), shorting());
for_each(s1.begin(), s1.end(), ptrstr);
s1.push_back("^_^");
cout << endl;
for_each(s1.begin(), s1.end(), ptrstr);
cout << endl;
//lambda表达式
stable_sort(s1.begin(), s1.end(),
[](const string &str1, const string &str2) {
return str1.size() < str2.size(); });
for_each(s1.begin(), s1.end(), ptrstr);
cout << endl;
MyVector<string> s2(s1);
s2.push_back("!");
s2.push_back("!");
s2.push_back("!");
cout << " the size is " << s2.size() << " the capacity is: " << s2.capactiy() << endl;
for (auto c : s2)
cout << c << " ";
cout << endl;
cout << "末尾元素" << s2.back() << endl;
s2.pop_back();
s2.pop_back();
s2.pop_back();
cout << " the size is " << s2.size() << " the capacity is: " << s2.capactiy() << endl;
//测试初始化列表
MyVector<int> num = {128,256,512,1024};
for (auto c : num)
cout << c << " ";
cout << endl;
//测试[]操作符
MyVector<string> s4;
s4.push_back("hehe");
const MyVector<string> s5 = s4;
s4[0] = "hehehe";
printString pterr(cerr, '\n');
pterr(s5[0]);
printString prt;//默认使用打印到cout
prt(s4[0]);//将s4[0]传递给operator()(string)
}
int main()
{
MyVector_opt();
return 0;
}
测试结果:
参考:
c++ primer
c++ Reference