C++STL中Vector常用函数
2017-02-22 20:55
369 查看
//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)
- C++ Standard Stl -- SGI STL源码学习笔记(07) stl_vector 与 一些问题的细化 3 resize函数剖析
- 【转】 C++STL 常用 函数 用法
- C++ STL 常用方法(函数)之-map篇
- STL之Vector(三):Vector常用函数
- C++ STL 常用 函数 用法
- C++中常用的STL 函数
- C++STL中vector容器 assign()函数的用法
- C++STL 常用 函数 用法
- 从零开始学C++之STL(三):迭代器类vector::iterator 和 vector::reverse_iterator 的实现、迭代器类型、常用的容器成员
- 【C++】STL常用容器总结之三:向量vector
- c++ stl string 常用函数
- C++ STL之vector常用指令
- C++STL 常用 函数 用法
- stl 常用函数(包括vector list stack queue)
- C++STL 常用 函数 用法
- 面试准备(常用函数和数据结构)C++Vector用法
- C++ STL常用函数用法
- C++STL中vector容器 begin()与end()函数、front()与back()的用法
- stl 常用函数(包括vector list stack queue)