vector即動(dòng)態(tài)數(shù)組,,也叫向量,。 直接上代碼! #include<iostream> #include<vector> #include<algorithm> using namespace std; int main() { //構(gòu)造 vector<int> v1(3); //構(gòu)造一個(gè)大小為3的向量,,不賦值默認(rèn)為0 for (vector<int>::iterator it = v1.begin(); it < v1.end(); it++) //輸出:000 cout << *it; cout << endl; vector<int> v2{ 2,6,8 }; //賦值構(gòu)造 for (vector<int>::iterator it = v2.begin(); it < v2.end(); it++) //輸出:268 cout << *it; cout << endl << v2.size() << endl; //size=3 //重置大小 v2.resize(4); for (vector<int>::iterator it = v2.begin(); it < v2.end(); it++) //輸出:2680 cout << *it; cout << endl << v2.size() << endl; //size=4 //元素獲取 cout << v2[1] << endl; //不檢查下標(biāo)是否越界,但速度較快 cout << v2.at(1) << endl; //檢查下標(biāo)是否越界 cout << v2.front() << endl; //輸出:2 cout << v2.back() << endl; //輸出:0 //追加 v2.push_back(9); for (vector<int>::iterator it = v2.begin(); it < v2.end(); it++) //輸出:26809 cout << *it; cout << endl << v2.size() << endl; //size:5 //刪除 v2.erase(v2.end() - 2); for (vector<int>::iterator it = v2.begin(); it < v2.end(); it++) //輸出:2689 cout << *it; cout << endl << v2.size() << endl; //size:4 v2.clear(); for (vector<int>::iterator it = v2.begin(); it < v2.end(); it++) //無輸出 cout << *it; cout << endl << v2.size() << endl; //size:0 //排序 v2 = { 2,6,8,3,6,9 }; sort(v2.begin(), v2.end()); //從小到大排序 for (vector<int>::iterator it = v2.begin(); it < v2.end(); it++) //輸出:236689 cout << *it; cout << endl; sort(v2.begin(), v2.end(),greater<int>()); //從大到小排序 for (vector<int>::iterator it = v2.begin(); it < v2.end(); it++) //輸出:986632 cout << *it; cout << endl; return 0; } |
|