Summary of the basic usage of STL container vector and stl container vector
According to ACM program design, we use examples to demonstrate vector usage.
Methods: push_back (), insert (), erase (), clear (), size (), empty ();
Algorithm: reverse (), sort (), accumulate ().
1 # include <vector> 2 # include <iostream> 3 # include <algorithm> // sort, reverse algorithm 4 # include <numeric> // accumulate algorithm 5 using namespace std; 6 template <typename T> 7 void printVec (const vector <T> & v) {// function template output vector 8 for (int I = 0; I <v. size (); I ++) 9 cout <v [I] <''; 10 cout <endl; 11} 12 13 int main () {14 vector <int> iv; // defines the vector 15 iv. push_back (2); // append new elements to the end 16 iv. push_back (7); 17 iv. push_back (3); 18 iv. Push_back (4); 19 iv. push_back (1); 20 iv. push_back (9); 21 cout <iv [2] <endl; // subscript access element 22 23 vector <double> dv (3 ); // defines the vector 24 cout <dv [2] <endl; // The default value is 0 25 26 vector <double> dv1 (6, 7.18 ); // define the vector 27 cout <dv1 [2] <endl; // default value: 7.1828 29 vector <int>: iterator it; // iterator output vector 30 for (it = iv. begin (); it! = Iv. end (); it ++) 31 cout <* it <''; 32 cout <endl; 33 cout <accumulate (iv. begin (), iv. end (), 0); 34 // use accumulate to sum 35 36 iv. insert (iv. begin (), 8); // insert 837 iv before the first element. insert (iv. begin () + 3rd); // insert 638 iv before elements. insert (iv. end (), 5); // insert 539 printVec (iv) before the last element; // call the printVec function 40 41 dv1.erase (dv1.begin () + 3 ); // delete an element 42 printVec (dv1); 43 44 45 dv1.erase (dv1.begin () + 2, dv1.end ()-1 ); // Delete multiple elements (including the left value but not the right value) 46 printVec (dv1); 47 cout <endl; 48 49 dv1.clear (); // empty the vector 50 cout <dv1.size () <''<dv1.empty () <endl; 51 // returns the number of elements/whether the vector is null 52 53 reverse (iv. begin (), iv. end (); // use the reverse Sorting Algorithm 54 printVec (iv); 55 56 sort (iv. begin (), iv. end (); // use sort to sort 57 printVec (iv) in ascending order; 58 return 0; 59}