作业:一、手动封装vector容器
二、思维导图
一、手动封装vector容器
文章来源:https://www.toymoban.com/news/detail-608866.html
源码:
#include <iostream>
using namespace std;
template < typename T >
class My_vector{
private:
T *first;
T *last;
T *end;
public:
My_vector<T>() : first(new T[2]), last(first), end(first + 2) {} //无参构造
My_vector<T>(int size) : first(new T[size]), last(first), end(first + size) {} //有参构造
//析构函数
~My_vector<T>(){
delete []first;
}
//拷贝构造
My_vector<T>(const My_vector &other){
int len = other.last - other.first;
int size = other.end - other.first;
this->first = new T[size];
memcpy(this->first, other.first, sizeof(T) * len);
this->last = this->first + len;
this->end = this->first + size;
}
//拷贝赋值
My_vector &operator = (const My_vector &other){
if(this == &other){
return *this;
}
delete []this->first;
this->first = other.first;
this->last = other.last;
this->end = other.end;
return *this;
}
//返回指定坐标的值
T &at(int index){
int len = last - first;
if(index < 0 || index > len){
throw -1;
}
return first[index];
}
//判空
bool empty(){
return first == last;
}
//判满
bool full(){
return last == end;
}
//返回第一个元素
T &front(){
return *first;
}
//返回最后一个元素
T &back(){
return *(last - 1);
}
//返回容器元素个数
int size(){
return last -first;
}
//清空vector容器
void clear(){
last = first;
cout << "清空容器成功!" << endl;
}
//二倍扩容
void expand(){
int size = end - first;
T *temp = new T[2 * size];
memcpy(temp, first, size * sizeof(T));
delete []first;
first = temp;
last = first + size;
end = first + 2 * size;
}
//尾插
void push_back(T data){
if(full()){
expand();
}
*last = data;
last++;
cout << "插入成功!尾插元素为:" << data << endl;
}
//尾删
void pop_back(){
if(empty()){
cout << "容器为空,无法删除!" << endl;
return;
}
--last;
cout << "删除成功!尾删元素为:" << *last << endl;
}
//遍历
void output(){
if(empty()){
cout << "容器内无元素!" << endl;
return;
}
int len = last - first;
cout << "容器内元素为:" << endl;
for(int i = 0; i < len; i++){
cout << first[i] << " ";
}
cout << endl;
}
};
int main()
{
int n;
cout << "请输入容器的大小: ";
cin >> n;
My_vector<int> v1(n); //实例化对象 有参构造
//尾插元素
v1.push_back(1);
v1.push_back(2);
v1.push_back(3);
v1.push_back(4);
v1.push_back(5);
v1.push_back(6);
v1.output();
//尾删元素
v1.pop_back();
v1.pop_back();
v1.output();
cout << "第一个元素的值为:" << v1.front() << endl;
cout << "最后一个元素的值为:" << v1.back() << endl;
cout << "元素容器个数为:" << v1.size() << endl;
v1.clear(); //清空容器
v1.output();
return 0;
}
二、思维导图
文章来源地址https://www.toymoban.com/news/detail-608866.html
到了这里,关于嵌入式:C++ Day7的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!