C++ Vector common basic operations

  • 2020-05-30 20:55:10
  • OfStack

The standard library vector type is the type 1 template which is mostly used in C++, and vector type is equivalent to a kind of dynamic container. In vector, there are mainly 1 basic operations, which are introduced in this paper. The specific contents are as follows:

(1) header #include < vector > .

(2) create vector object, vector < int > vec;

(3) insert a number at the end: vec.push_back (a);

(4) use subscripts to access elements, cout < < vec[0] < < endl; Remember the index starts at 0.

(5) use iterators to access elements.


vector<int>::iterator it;
for(it=vec.begin();it!=vec.end();it++)
cout<<*it<<endl;

(6) insert element: vec.insert (vec.begin ()+i,a); Insert a before the i+1 element;

(7) delete element: vec.erase (vec.begin ()+2); Delete the third element


vec.erase(vec.begin()+i,vec.end()+j); Delete interval [i,j-1]; Range from 0 start 

(8) vector size: vec.size ();

(9) to empty: vec clear ();

Here's a simple example:


#include<iostream>
#include<stdio.h>
#include<vector>// Indefinite array, vector 
#include<string>
using namespace std;
int main()
{
  vector<string> v;
  string temp;
  cout<<" Please enter the 1 And press enter Ctrl+Z Represents the end of the cycle: "<<endl;
  while(getline(cin,temp))//Ctrl+Z  End of cycle 
  {
    v.push_back(temp);
  }
  vector<string>::iterator t; // define 1 An iterator t
  t=v.begin();
  for(t;t!=v.end();t++)
  {
    (*t)[0]=toupper((*t)[0]);// To start the first 1 Capital letters 
    cout<<*t<<endl;
  }
  return 0;
}
/* Main functions: input 1 String, and then output 1 And capitalize the first letter 
 Input example: 
ginger,you are the best!
^Z
 Output: 
Ginger,you are the best!
*/

conclusion


Related articles: