1.利用模板类完成顺序表
#include <iostream>
using namespace std;
#define Max 5
template <typename T>
class A
{
public:
T data[Max];
T len;
//构造
A(T len):len(len)
{
}
//析构
~A()
{
}
//
T set_A(T a);
void get_A();
void deleA();
T serchA(T a);
};
template <typename T>
T A<T>::set_A(T a)
{
data[len]=a;
len++;
return 0;
}
//尾删
template <typename T>
void A<T>::deleA()
{
len--;
}
//遍历
template <typename T>
void A<T>::get_A()
{
for (int i=0;i<len;i++) {
cout<<data[i]<<" ";
}
}
//查
template <typename T>
T A<T>::serchA(T a)
{
if(a>len||a<0)
{
cout<<"输入的下标有误"<<endl;
return -1;
}
return data[a];
}
int main()
{
int a = 0;
A<int> a1(0);
int cc = 0;
cout<<"要输入个数";
cin>>cc;
for (int i = 0;i <cc;i++) {
if(a1.len == Max)
{
cout<<"表已满"<<endl;
break;
}
cout<<"要输入第"<<i+1<<"个的值";
cin>>a;
a1.set_A(a);
}
a1.get_A();
cout<<endl;
a1.deleA();
cout<<endl;
a1.get_A();
cout<<endl;
cout<<"输入要查找的下标"<<endl;
int sub;
cin>>sub;
if(a1.serchA(sub)!= -1)
{
cout<<"下标"<<sub<<"的值为"<<a1.serchA(sub)<<endl;
}
return 0;
}
2.课上代码整理
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> v1;//实例化容器类对象
v1.assign(4,101);//给v1赋4个值为101的元素。
cout<<"v1第一个元素"<<v1.front()<<endl;
//at返回值为引用,对其进行修改 111
v1.at(1)=111;
cout<<v1.at(1)<<endl;
cout<<"最末元素为"<<v1.back()<<endl;
v1.at(0)=115;
//起始元素的值
cout<<*(v1.begin())<<endl;
//调用end函数查看最末元素
cout<<*(v1.end()-1)<<endl;
//capacity
cout<<v1.capacity()<<endl; //4
v1.push_back(99);
cout<<v1.capacity()<<endl; //2倍扩容 8
//size容纳元素的数目
cout<<v1.size()<<endl; //5
//迭代器访问所有元素
vector<int>::iterator it;
int i = 0;
it = v1.begin();
for (int i = 0;i<v1.size();i++) {
cout<< *it++ <<endl;
}
vector<int> v3(v1.begin(),v1.end()-2);
it=v3.begin();
cout << "v3的结果:" << endl;
for(i=0;i<v3.size();i++)
{
cout << *it++ << endl;
}
return 0;
}