作業(yè):一、手動(dòng)封裝vector容器
? ? ? ? ?? 二、思維導(dǎo)圖
一、手動(dòng)封裝vector容器
文章來(lái)源:http://www.zghlxwxcb.cn/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) {} //無(wú)參構(gòu)造
My_vector<T>(int size) : first(new T[size]), last(first), end(first + size) {} //有參構(gòu)造
//析構(gòu)函數(shù)
~My_vector<T>(){
delete []first;
}
//拷貝構(gòu)造
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;
}
//返回指定坐標(biāo)的值
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;
}
//返回第一個(gè)元素
T &front(){
return *first;
}
//返回最后一個(gè)元素
T &back(){
return *(last - 1);
}
//返回容器元素個(gè)數(shù)
int size(){
return last -first;
}
//清空vector容器
void clear(){
last = first;
cout << "清空容器成功!" << endl;
}
//二倍擴(kuò)容
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 << "容器為空,無(wú)法刪除!" << endl;
return;
}
--last;
cout << "刪除成功!尾刪元素為:" << *last << endl;
}
//遍歷
void output(){
if(empty()){
cout << "容器內(nèi)無(wú)元素!" << endl;
return;
}
int len = last - first;
cout << "容器內(nèi)元素為:" << endl;
for(int i = 0; i < len; i++){
cout << first[i] << " ";
}
cout << endl;
}
};
int main()
{
int n;
cout << "請(qǐng)輸入容器的大小: ";
cin >> n;
My_vector<int> v1(n); //實(shí)例化對(duì)象 有參構(gòu)造
//尾插元素
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 << "第一個(gè)元素的值為:" << v1.front() << endl;
cout << "最后一個(gè)元素的值為:" << v1.back() << endl;
cout << "元素容器個(gè)數(shù)為:" << v1.size() << endl;
v1.clear(); //清空容器
v1.output();
return 0;
}
二、思維導(dǎo)圖
文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-608866.html
到了這里,關(guān)于嵌入式:C++ Day7的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!