vector容器主要的功能函数:
#include <iostream>
#include <vector>
using namespace std;int main()
{//无参构造vector <int> v1;//有参构造vector <int> v2(5,99);//判空cout<<v1.empty()<<endl;//1cout<<v2.empty()<<endl;//0//访问容器中的第一个元素cout<<v2.front()<<endl;//99//给v1赋4个值,值为30v1.assign(4,30);//访问容器中的最后一个元素cout<<v1.back()<<endl;//30//用at()函数,赋值给对应下标v1.at(3)=25;cout<<v1.back()<<endl;//25v1.at(0)=60;//用begin()查看第一个元素,属于迭代器,类似于指针cout<<*(v1.begin())<<endl;//end()-1才是容器中的最后一个元素,属于迭代器,类似于指针cout<<*(--v2.end())<<endl;//99//capacity(),返回重新分配内存前的个数cout<<v1.capacity()<<endl;//4//push_back(),vector容器的二倍扩容v1.push_back(66);cout<<*(--v1.end())<<endl;//66cout<<v1.capacity()<<endl;//容器大小由4到8,二倍阔容,但66用了一个空间5v1.push_back(77);//77用了一个空间6cout<<v1.capacity()<<endl;//容器大小还是8,还没用完,剩两个cout<<v1.size()<<endl;//6cout<<"-------------"<<endl;//用迭代器访问所有元素vector<int>::iterator it;//it 是迭代器unsigned int i=0;for(i=0,it=v1.begin();i<v1.size();i++,it++){cout<<*it<<endl;}vector<int> v3(v1.begin(),v1.end()-2);cout<<"-------------"<<endl;cout<<"v3:"<<endl;for(i=0,it=v3.begin();i<v3.size();i++,it++){cout<<*it<<endl;}return 0;
}
用模板类实现顺序表:
#include <iostream>
#define Maxsize 5
using namespace std;
template <typename T>
class sqlist
{T arr[Maxsize];int len=0;
public:bool empty();//判空bool full();//判满bool insert_rear(T);//尾插bool delete_rear();//尾删int find_key(T);//按元素查找void show();};
//empty
template<typename T>
bool sqlist<T>::empty()
{if(len<=0){cout<<"sqlist为空"<<endl;return true;}else{return false;}
}
//full
template<typename T>
bool sqlist<T>::full()
{if(len>=Maxsize){cout<<"sqlist为满"<<endl;return true;}else{return false;}}template<typename T>
bool sqlist<T>::insert_rear(T element)
{if(full()){cout<<"sqlist为满"<<endl;return false;}arr[len]=element;len++;return true;
}template<typename T>
bool sqlist<T>::delete_rear()
{if(empty()){cout<<"sqlist为空"<<endl;return false;}len--;return true;
}template<typename T>
int sqlist<T>::find_key(T element)
{if(empty()){cout<<"sqlist为空"<<endl;return false;}for(int i=0;i<len;i++){if(arr[i]==element){return i;}}return -1;
}
template<typename T>
void sqlist<T>::show()
{for(int i=0;i<len;i++){cout<<arr[i]<<endl;}cout<<"------"<<endl;
}
int main()
{sqlist <int>a;a.insert_rear(5);a.insert_rear(3);a.insert_rear(8);a.insert_rear(9);a.show();a.delete_rear();a.show();cout<<a.find_key(3)<<endl;return 0;
}
c++day6 - 幕布