Vector is a container in C + + that replaces a built-in array.
It is part of the C + + standard library.
You must include a preprocessing #include<vector> when you use it.
Vectors are used in two ways:
1. Vector<int> Vector (elem_size)
The contents of the parentheses of this method can be more than just the number of elements.
The vector cannot be initialized like an array in C.
int array[6] = {1, 2, 3, 4, 5, 6};
But you can initialize an existing array to the vector:
Vector<int> vector (array, array+6);
or initialize a portion of the array to the vector:
Vector<int> Vector (array+1, array+4);
Part of the value of the copy here is: 2,3,4 (top 3 digits, but the value of the 3 digits is somewhat strange)
Note: The values in parentheses are pointers.
Example:
1 #include <stdio.h>
2 #include <vector>
3 #include <iostream>
4 #include <string>
5
6 using namespace Std;
7
8 int Main ()
9 {
Ten int i = 0;
One vector<string> v;
//for (i = 0; i < i++) {
//V.push_back ("Wanglei");//load element into vector
14//}
string Word;
for (int i=0 i < ++i) {
CIN >> Word;
V.push_back (word);
19}
cout << "Words read are:/n";
for (Vector<string>::iterator it = V.begin (); it!= v.end (); ++it) {
cout << *it << ';
23}
cout << Endl;
25
for (i = 0; i < v.size (); i++) {
cout << V[i] << "";
28}
29
cout << Endl;
The first use of//vector: A method similar to a built-in array
const int elem_size = 10;
array[elem_size int] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
Vector<int> vector (array, array+10);
//for (int i=0 i < elem_size; ++i) {
+//Vector[i] = V[i];
37//}
for (int i=0 i < elem_size; ++i) {
cout << Vector[i];
40}
cout << Endl;
0;
43}
Compiling: $ g++ A.C
Run: $./a.out
Results:
Enter a text:
Hello world! I ' m a C + + programmer. How do I do? My name is..
Words Read are:
Hello world! I ' m a C + + programmer. How do I do?
Hello world! I ' m a C + + programmer. How do I do?
Pointers as parameters for the vector constructor:
0123456789
2. STL Usage:
Define an empty vector
vector<string> text;
The elements are then added through the push_back () function.
Example
15 string Word;
16 for (int i=0 i < ++i) {
17 & nbsp; cin >> Word;
18 v.push_back (word);
19 }
20 cout << "Words read are:/n";
21 for (Vector<string>::iterator it = V.begin (); it!= v.end (); ++it) {
22 cout << *it << ';
23 }
24 cout << Endl;