首页 > 编程语言 > 详细

【C++】STL之vector类

时间:2017-02-15 16:26:00      阅读:160      评论:0      收藏:0      [点我收藏+]

vector类,相当于不定长的数组,并与其一样支持随机访问。

 

vector的初始化:

vector<int> v{1,2,3,4,5}; // 列表初始化
vector<int> v2(5,0); // v2含有5个元素,每个都是0

 

一些操作:

vec.push_back(val); // 在末尾插入一个元素
vec.pop_back(val); // 弹出末尾的一个元素
vec.front() // 获取首元素
vec.back() // 获取末尾元素
vec.size() // 返回大小
vec.empty // 返回是否为空
vec.clear(); // 清空

 

迭代器:

vector<int>::iterator itB = v1.begin();
cout << "The first element of the vector is " << *itB << \n;    
vector<int>::iterator itE = v1.end(); cout << "The last element of the vector is " << *(itE - 1) << \n << endl;

反向迭代器:

auto itRB = v1.rbegin(), itRE = v1.rend();
cout << "The first element of the vector is " << *(itRE - 1) << \n;
cout << "The last element of the vector is " << *(itRB) << \n << endl;

 

排序:

vector<int> v2{ 2,1,5,3,4 };
sort(v2.begin(), v2.end());

 

去重:

vector<int> v3{ 1,1,1,2,2,3 };
// unique()函数返回一个迭代器,指向重复元素的开头
auto ituv=unique(v3.begin(), v3.end());
//用erase函数擦除重复的元素
v3.erase(ituv, v3.end());

 

一段测试代码:

技术分享
 1 #include <iostream>
 2 #include <vector>
 3 #include <algorithm>
 4 #include <iterator>
 5 using namespace std;
 6 void show(vector<int> v) {
 7     for (auto i : v) {
 8         cout << i <<  ;
 9     }
10     cout << endl;
11 }
12 void fill(vector<int> v) {
13     for (int i = 1; i <= 10; i++) {
14         v.push_back(i);
15     }
16 }
17 int main(void)
18 {
19     ios::sync_with_stdio(false);
20     cin.tie(false);
21 
22     vector<int> v1;
23         
24     fill(v1);
25 
26     cout << "The first element of the vector is " << v1.front() << \n;
27     cout << "The last element of the vector is " << v1.back() << \n;
28     cout << "The size of the vector is " << v1.size() << \n << endl;
29 
30     cout << "The vector is" << (v1.empty() ? " " : " not ") << "empty." << "\n";
31     v1.clear();
32     cout << "The vector is" << (v1.empty() ? " " : " not ") << "empty." << "\n" << endl;
33 
34     fill(v1);
35 
36     vector<int>::iterator itB = v1.begin();
37     cout << "The first element of the vector is " << *itB << \n;
38     vector<int>::iterator itE = v1.end();
39     cout << "The last element of the vector is " << *(itE - 1) << \n << endl;
40     // 反向迭代器
41     auto itRB = v1.rbegin(), itRE = v1.rend();
42     cout << "The first element of the vector is " << *(itRE - 1) << \n;
43     cout << "The last element of the vector is " << *(itRB) << \n << endl;
44 
45     vector<int> v2{ 2,1,5,3,4 };
46     sort(v2.begin(), v2.end());
47     show(v2);
48 
49     vector<int> v3{ 1,1,1,2,2,3 };
50     // unique()函数返回一个迭代器,指向重复元素的开头
51     auto ituv=unique(v3.begin(), v3.end());
52     v3.erase(ituv, v3.end());
53     show(v3);
54     
55     return 0;
56 }
View Code

【C++】STL之vector类

原文:http://www.cnblogs.com/ray-coding-in-rays/p/6401854.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!