vector类

vector基本用法:

vector是一种向量类型,可容纳多种数据类型,使用需包含头文件<vector>

vector的构造:

 

 1 #include <iostream>
 2 #include <vector>
 3 using namespace std;
 4 int main()
 5 {
 6     vector<int> a(10); // 定义10个元素,初值不确定
 7     vector<int> b(10,1); // 初值为1
 8     vector<int> a(b); // 用向量b来创建a,相当于整体复制赋值
 9     // 定义a的值为b中0到2个元素
10     vector<int> a(b.begin(),b.begin()+3)
11     int c[3] = {1,2,3};
12     vector<int> a(c,c+3); // 从数组中获得初值
13     return 0;
14 }

 

vector常用操作:

 

 1 #include <iostream>
 2 #include <vector>
 3 using namespace std;
 4 int main()
 5 {
 6     int b[] = {1,2,3,4,5};
 7     vector<int> a(b,b+5);
 8     cout << a.back() << endl; //返回最后一个元素
 9     cout << a.front() << endl;//返回第一个元素
10     cout << a[2] << endl; // 返回第3个元素
11     // 判空
12     if(!a.empty()) cout << "Not empty" << endl;
13     a.pop_back(); // 删除a的最后一个元素
14     a.push_back(6);//在a最后插入元素6
15     cout << a.size() << endl; // 元素个数
16     cout << a.capacity() << endl;// 内存中总共可容纳的元素个数
17     a.resize(10); // 将现有元素个数调至10个,多删少补
18     a.resize(10,2); // 调至10个,其值为2
19     /*
20      * a.swap(b); b为向量,将a中元素和b中元素进行整体交换
21      * a==b a,b都为向量,进行比较操作:!= >= <= > <
22     */
23     a.clear(); // 清除所有元素
24     return 0;
25 }

 

vector的遍历:

 

 1 #include <iostream>
 2 #include <vector>
 3 using namespace std;
 4 int main()
 5 {
 6     int b[] = {1,2,3,4,5};
 7     vector<int> a(b,b+5);
 8     // 循环遍历
 9     for(int i = 0; i < a.size(); i++)
10         cout << a[i] << " ";
11     cout << endl;
12     // 迭代器遍历
13     for(vector<int>::iterator it = a.begin(); it != a.end(); it++)
14         cout << *it << " ";
15     return 0;
16 }

 

可用的一些小算法:

 1 #include <iostream>
 2 #include <vector>
 3 #include <algorithm> // 注意包含头文件
 4 using namespace std;
 5 int main()
 6 {
 7     int b[] = {1,2,3,4,5};
 8     vector<int> a(b,b+5);
 9     sort(a.begin(),a.end()); // 排序
10     reverse(a.begin(),a.end()); // 反转
11     return 0;
12 }

 

posted @ 2020-08-09 11:24  不敢说的梦  阅读(232)  评论(0)    收藏  举报