【C++】STL之vector类
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 }