赞
踩
(一)了解vector
vector是一个容器,可容纳不同的类型;
常见操作是初始化、push_back/pop_back/insert/erase/clear data to vector、各种正反向遍历、排序与二维定义及遍历。
(二)Test Demo
- #include <iostream>
- #include <vector>
- #include <algorithm>
-
- using namespace std;
-
- int main()
- {
- cout << "*********************Demo1:initial a vector************************" << endl;
- vector<int> a;
- vector<char> b;
- vector<int> c = a, d(a);
- vector<int> e(3, 1), f(3);
- vector<int> g = {1, 2, 3, 4}, h{ 1, 2, 3, 4 };
-
- cout << "*********************Demo2:vector options************************" << endl;
- cout << "(1)push_back/pop_back/insert/erase/clear data to vector" << endl;
- for (size_t i = 0; i < 5; i++)
- {
- a.push_back(i);
- }
- cout << "(2)遍历 vector" << endl;
- for (auto it:a) {
- cout << it;//auto默认为int 故it不用解引用
- }
- cout << endl;
- for (vector<int>::iterator it = a.begin(); it != a.end(); ++it) {
- cout << *it;
- }
- cout << endl;
- cout << "使用反向迭代器" << endl;
- for (auto rit = a.rbegin(); rit != a.rend(); ++rit) {//注意注意迭代器是反向+
- cout << *rit;
- }
- //还可以用a.at(index); or a[index];
- int aaa = a.at(a.size()-1);
- cout << "尾部元素" << aaa << endl;
-
- cout << "*********************Demo3:vector sort************************" << endl;
- vector<int> num{1, 3, 1, 8, 4, 2};
- cout << "sort:";
- sort(num.begin(), num.end());//sort 与reverse 参数必须传入vector的地址,函数定义在algorithm中
- for (auto it : num)
- cout << it;
- cout << endl;
- cout << "reverse:";
- reverse(num.begin(), num.end());
- for (auto it : num)
- cout << it;
- cout << endl;
-
- cout << "*********************Demo4:vector 二维定义************************" << endl;
- vector<vector<int>> twoarray(5, vector<int>(6));//5*6
- for (vector<vector<int>>::iterator it = twoarray.begin(); it != twoarray.end(); ++it) {
- /*for (auto it1 :*it) {
- it1 = int(rand()&0xff) ;
- }*/
- for (vector<int>::iterator it1 = (*it).begin(); it1 != (*it).end(); ++it1) {
- *it1 = int(rand()&0xFF);
- }
- }
- cout << endl;
- for (auto it:twoarray) {
- for (auto it1 : it) {
- cout << it1 << " ";
- }
- cout << endl;
- }
- cout << endl;
-
- return 0;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。