STL(Standard Template Library即,模板库)包括六个部分:容器(containers)、迭代器(iterators)、空间配置器(allocator)、配接器(adapters)、算法(algorithms)、仿函数(functors)

vector

1、vector:连续存储

(1)头文件,#include<vector>

(2)创建vector对象,vector<int> vec;

(3)尾部插入元素,vec.push_back(a);

(4)使用下标访问元素,cout<<vec[0]<<endl;

(5)使用迭代访问元素

 1 vector<int>::iterator it;
 2 for(it=vec.begin();it!=vec.end();it++)
 3     cout<<(*it)<<endl;

(6)插入元素,vec.insert(vec.begin()+i,a);在第i+1个元素前面插入a

(7)删除元素,vec.erase(vec.begin()+2);删除第3个元素

         vec.erase(vec.begin()+i,vec.end()+j);删除区间[i,j-1];区间从0开始

(8)向量大小,vec.size();

(9)清空,vec.clear();

 vector的元素不仅仅只限于int型,int、double、string、全局结构体等都可以。

 1 #include<iostream>
 2 #include<vector>
 3 using namespace std;
 4 
 5 struct Student
 6 {
 7     int num;
 8     double score;
 9     double operator< (const Student &stu) const
10     {
11         if(stu.score>score)
12             return stu.score;
13         else
14             return score;
15     }
16 };
17 
18 int main()
19 {
20     vector<Student> stu;
21     //student 1
22     Student stu_temp;
23     stu_temp.num = 1;
24     stu_temp.score =9.9;
25     stu.push_back(stu_temp);
26     //student 2
27     Student stu_temp1;
28     stu_temp1.num = 2;
29     stu_temp1.score =8.8;
30     stu.push_back(stu_temp1);
31     //student 3
32     Student stu_temp2;
33     stu_temp2.num = 3;
34     stu_temp2.score =7.7;
35     stu.push_back(stu_temp2);
36     //print all the students
37     cout<<"the number of student:"<<stu.size()<<endl;
38     vector<Student>::iterator it;
39     for(it=stu.begin();it!=stu.end();it++)
40         cout<<"number:"<<(*it).num<<" score:"<<(*it).score<<endl;
41     //delete one student
42     stu.erase(stu.begin()+1);
43     cout<<endl;
44     cout<<"the number of student:"<<stu.size()<<endl;
45     for(it=stu.begin();it!=stu.end();it++)
46         cout<<"number:"<<(*it).num<<" score:"<<(*it).score<<endl;
47     //print the better score
48     double _result = stu_temp<stu_temp1;
49     cout<<endl;
50     cout<<"the better score:"<<_result<<endl;
51 
52     return 0;
53 }
vector_sample

相关文章: