A few days ago, a user asked me how to use the vector in C ++. Now, I will make a brief summary of the vector and share it with csdn users. Note: things are relatively simple. If you are a good user, please close this page directly!
First, the vector declaration:
# Include <vector>
Using namespace STD; // declare it here
...
Vector <int> I;
...
Or
# Include <vector>
...
STD: vector <int> I; // explicitly declare
See the specific usage:
1. Storage and output of Vector Data:
Vector <cstring> V; <br/> for (INT I = 0; I <40; I ++) <br/>{< br/> cstring S; <br/> S. format ("% d", I); <br/> v. push_back (s); <br/>}< br/> cstring SS; <br/> for (Int J = 0; j <v. size (); j ++) <br/>{< br/> SS + = V [J] + ","; <br/>}< br/> MessageBox (SS );
Note: You can also use v. Begin () and V. End () to obtain the pointer positions of the starting and ending element addresses of a vector. You can also do this:
Vector <cstring> V; <br/> for (INT I = 0; I <40; I ++) <br/>{< br/> cstring S; <br/> S. format ("% d", I); <br/> v. push_back (s); <br/>}< br/> cstring SS; <br/> vector <cstring >:: iterator ITER; <br/> for (iter = v. begin (); iter! = V. end (); ITER ++) <br/>{< br/> SS ++ = * ITER + ","; <br/>}< br/> MessageBox (SS );
2. Definition of two-dimensional vector (fixed length at the beginning)
Vector <vector <cstring> array (10, vector <cstring> (0); <br/> for (Int J = 0; j <10; j ++) <br/>{< br/> for (INT I = 0; I <9; I ++) <br/>{< br/> cstring S; <br/> S. format ("% d", I); <br/> array [I]. push_back (s); <br/>}</P> <p> cstring SS; <br/> for (int jj = 0; JJ <10; JJ ++) <br/>{< br/> for (int ii = 0; II <array [JJ]. size (); II ++) <br/>{< br/> SS + = array [JJ] [II]; <br/>}< br/> MessageBox (SS );
3. Define an array in which rows and columns are changed.
Int I = 0, j = 0; <br/> vector <cstring> array; <br/> vector <cstring> line; <br/> for (j = 0; j <10; j ++) <br/>{< br/> array. push_back (line); // initialize each vector; otherwise, the elements cannot be saved. <Br/> for (I = 0; I <9; I ++) <br/>{< br/> cstring s; <br/> S. format ("% d", I); <br/> array [J]. push_back (s); <br/>}</P> <p> cstring SS; <br/> for (int jj = 0; JJ <array. size (); JJ ++) <br/>{< br/> for (int ii = 0; II <array [JJ]. size (); II ++) <br/>{< br/> SS + = array [JJ] [II]; <br/>}< br/> MessageBox (SS );