//vector标准模板库使用
#include <iostream>
#include<list> //链表头文件
#include<string>
using namespace std;
//全局函数作为比较策略
bool Comp(string a, string b)
{
return a>b;
}
//定义仿函数当做比较策略
class Cop
{
public:
Cop() {}
bool operator()(string a, string b)
{
return a>b;
}
};
int main()
{
//使用无参构造,构造出一个链表
list<string> s1; //定义一个链表,每个元素都是一个字符串
//判空函数
if(s1.empty())
{
cout<<"the list is empty"<<endl;
}else
{
cout<<"the list is not empty"<<endl;
}
// 大小
cout<<"size of s1 = "<<s1.size()<<endl; //0
cout<<"max_size of s1 = "<<s1.max_size()<<endl; // 最多容纳的节点数
//头插
s1.push_front("hello");
s1.push_front("world");
//遍历
for(auto val:s1)
{
cout<<val<<" ";
}
cout<<endl;
//尾插
s1.push_back("I");
s1.push_back("love");
s1.push_back("China");
for(auto val:s1)
{
cout<<val<<" ";
}
cout<<endl;
//头删
s1.pop_front(); //删除第一个节点
s1.pop_back(); //删除最后一个节点
//使用迭代器进行遍历
for(auto p=s1.begin(); p!=s1.end(); p++)
{
cout<<*p<<" ";
}
cout<<endl;
//获取第一个元素
s1.front() = "AAAAAA";
// 获取最后一个元素
s1.back() = "ZZZZZ";
for(auto val:s1)
{
cout<<val<<" ";
}
cout<<endl;
//按值删除
s1.remove("I");
for(auto val:s1)
{
cout<<val<<" ";
}
cout<<endl;
//将链表元素逆置
s1.reverse();
for(auto val:s1)
{
cout<<val<<" ";
}
cout<<endl;
//插入数据
s1.insert(s1.begin(), "OOOOOOO");
s1.insert(s1.begin(), "KKKKKKKK");
for(auto val:s1)
{
cout<<val<<" ";
}
cout<<endl;
//调用排序函数
//s1.sort(); //默认是升序排序
//s1.sort(Comp); //加了比较策略的排序,全局函数作为策略
// s1.sort([](string a, string b){
// return a>b;
// });
s1.sort(Cop()); //使用仿函数当做比较策略
for(auto val:s1)
{
cout<<val<<" ";
}
cout<<endl;
s1.push_back("AAAAAA");
for(auto val:s1)
{
cout<<val<<" ";
}
cout<<endl;
// 调用去重函数
s1.unique();
for(auto val:s1)
{
cout<<val<<" ";
}
cout<<endl;
return 0;
}
//自己手写标准模板库vector
#include <iostream>
using namespace std;
template<typename T>
class Myvector
{
private:
T* first;
T* last;
T* end;
public:
//无参构造
Myvector() {}
//有参构造
Myvector(T* f,T* l,T* e):first(new T(f)),last(new T(l),end(new T(e))) {
cout<<"Myvector::有参构造"<<endl;
}
//析构函数
~Myvector(){
delete first;
cout<<"Myvector::析构函数"<<endl;
}
Myvector(const Myvector& other):first(new T(other.first)),last(new T(other.last),end(new T(other.end))){
cout<<"Myvector::拷贝构造"<<endl;
}
//定义拷贝赋值函数
Myvector& operator=(const Myvector &other){
if(this != &other){
this->first = new T( *(other.first));
this->last = new T( *(other.last));
//this->end = other.end;//浅拷贝
this->end= new T( *(other.end));//给指针成员单独开辟内存空间, 将原对象的空间中的值放入新的内存空间 深拷贝
}
cout<<"Myvector::拷贝赋值函数"<<endl;
return *this;
}
};
int main()
{
cout << "Hello World!" << endl;
return 0;
}