Basic Vector operations,

Source: Internet
Author: User

Basic Vector operations,


(1) header file # include <vector>.
(2) create a vector object, vector <int> vec;
(3) Insert numbers at the end: vec. push_back ();
(4) use a subscript to access the element. cout <vec [0] <endl; remember that the subscript starts from 0.
(5) use an iterator 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 3rd Elements
Vec. erase (vec. begin () + I, vec. end () + j); Delete interval [I, J-1]; interval starts from 0
(8) vector size: vec. size ();
(9) clear: vec. clear ();

The following is a simple example:

# Include <iostream> # include <stdio. h ># include <vector> // Variable Length array, vector # include <string> using namespace std; int main () {vector <string> v; string temp; cout <"enter a string and press Ctrl + Z to end the loop:" <endl; while (getline (cin, temp )) // Ctrl + Z end loop {v. push_back (temp);} vector <string>: iterator t; // defines an iterator t = v. begin (); for (t; t! = V. end (); t ++) {(* t) [0] = toupper (* t) [0]); // change the first letter at the beginning to uppercase cout <* t <endl;} return 0;}/* main function: enter a string and then output a string, input the first letter in uppercase: ginger, you are the best! ^ Z output: Ginger, you are the best! */

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.