目录
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> v1;
vector<int> v2(5,10);
cout << "判断V1是否为空:" <<v1.empty() << endl;
cout << "判断V2是否为空:"<< v2.empty() << endl;
cout << "v2起始元素:"<<v2.front() << endl;
cout << "v2最末元素:"<<v2.back() << endl;
v1.assign(5,20);//给v1中赋5个值为20的元素,原来的值会被覆盖
v1.at(0)=10;
v1.at(1)=20;
v1.at(2)=30;
v1.at(3)=40;
v1.at(4)=50;
cout << "v1.at(2)=" << v1.at(2) <<endl;; //返回指定位置的引用
cout << "调用begin:" << *(v1.begin()) << endl;
cout << "调用end:" << *(--v2.end()) << endl; //end函数返回的是,指向当前容器最后一个元素下一个位置的迭代器
cout <<"重新进行内存分配前所能容纳的元素数量:" << v1.capacity() << endl;
v1.push_back(123); //添加值为123的元素到v1末尾
cout <<"重新进行内存分配前所能容纳的元素数量:"<< v1.capacity() << endl; //vector容器的二倍扩容
cout << "v1容纳的元素数目:" <<v1.size() << endl;
cout << "v2容纳的元素数目:" <<v2.size() << endl;
cout << "利用迭代器访问所有元素 :" << endl;
vector<int>::iterator it; //定义一个指向int类型元素的迭代器it
unsigned int i = 0;
for(i=0,it=v1.begin();i<v1.size();i++,it++)
{
cout << *it << " ";
}
return 0;
}
#include <iostream>
using namespace std;
template <typename T>
class SeqList
{
private:
T* data; // 存放元素的数组
int maxSize; // 顺序表的最大容量
int len; // 顺序表的当前长度
public:
SeqList(int size)//构造函数
{
maxSize = size;
data = new T[maxSize];
len = 0;
}
~SeqList() //析构函数
{
delete data;
}
int length() //顺序表的当前长度
{
return len;
}
bool rear_insert(const T &element)//尾插
{
if(len==maxSize)
{
cout << "顺序表已满" << endl;
return false;
}
data[len]=element;
len++;
return true;
}
bool rear_delete() //尾删
{
if(len==0)
{
cout << "顺序表为空" << endl;
return false;
}
len--;
return true;
}
bool pos_insert(int pos, const T &element) { //按位置插入
if (pos < 0 || pos > len || len == maxSize)
{
return false;
}
for (int i = len - 1; i >= pos; i--)
{
data[i + 1] = data[i];
}
data[pos] = element;
len++;
return true;
}
bool delete_pos(int pos) { //按位置删除
if (pos < 0 || pos >= len)
{
return false;
}
for (int i = pos; i < len - 1; i++)
{
data[i] = data[i + 1];
}
len--;
return true;
}
void show() //遍历
{
if(len==0)
{
cout << "顺序表为空" << endl;
}else
{
for (int i = 0; i < len; i++)
{
cout << data[i] << " ";
}
cout << endl;
}
}
};
int main() {
SeqList<int> list(10);
list.pos_insert(0, 1);
list.pos_insert(1, 2);
list.pos_insert(2, 3);
list.rear_insert(5);
list.show();
list.rear_delete();
list.delete_pos(1);
list.show();
return 0;
}