//STL中Vector的用法
#include <iostream>
#include <vector> //Vec需要的头文件
#include <string> //用到<<输出string类型,必须有这个头文件
using namespace std;
struct MyStruct
{
int ID;
string Name;
//重写小于运算符
bool operator< (const MyStruct& other)
{
//判断是不是自己
if (ID != other.ID)
{
return false;
}
//按ID的大小排序
if (ID <= other.ID)
{
return true;
}
return false;
}
};
enum MyEnum
{
back = 10,
};
int main()
{
vector<MyStruct> MyVec; //创建容器
MyStruct MyData;
for (int i = 0; i < back; i++)
{
MyData.ID = i;
MyData.Name = "Ly";
MyVec.push_back(MyData); //1.push_back()插入函数,向Vec尾部插入元素。Vector本身不支持头插法
}
for (vector<MyStruct>::iterator it = MyVec.begin(); it != MyVec.end();) //2.Vec迭代器用法 begin()是第一个元素,end()是末端的下一个元素,back()是最后一个元素
{ //rbegin()可以把最后一个元素当做起点,rend()和rbegin()类似
cout << it->ID << " " << (*it).Name << endl;
it++;
}
MyData.ID = 20;
MyData.Name = "LL";
MyVec.assign(10, MyData); //算是一种赋值方法,会覆盖掉之前的数据
for (int j = 0; j < 3; j++)
{
MyVec.pop_back(); //3.pop_back()函数,从尾部依次删除元素
}
cout << "删除3个元素之后的数据" << endl;
for (vector<MyStruct>::iterator it = MyVec.begin(); it != MyVec.end();)
{
cout << it->ID << " " << (*it).Name << endl;
it++;
}
cout << "直接查找索引为3的数据: "<<MyVec.at(3).ID << endl; //4.查找下标为3的数据
MyVec.erase(MyVec.begin() + 1); //5.删除一个元素
MyVec.erase(MyVec.begin(), MyVec.begin() + 3); //5.删除从0到3的四个元素
for (vector<MyStruct>::iterator it = MyVec.begin(); it != MyVec.end();)
{
cout << it->ID << " " << (*it).Name << endl;
it++;
}
cout <<"求容器开辟的空间大小: "<< MyVec.capacity() << endl; //6.求容器开辟空间的大小
MyVec.reserve(MyVec.capacity()+3); //7.保留适当容量,可以在没有放数据之前使用,如果在已经分配了空间之后,这次修改只能比已经存在的大,不能小
cout << "求容器开辟的空间大小: " << MyVec.capacity() << endl; //6.求容器开辟空间的大小
cout << "求容器中元素的个数: " << MyVec.size() << endl; //8.求容器中元素的个数
MyVec.clear(); //9.清空容器
cout<<"容器是否为空:"<<MyVec.empty()<<endl; //10.判断容器是否为空
system("pause");
return 0;
}
C++STL中Vector常用函数
最新推荐文章于 2024-08-04 11:55:54 发布