11 | SS.push_back( "The number is 10" ); |
12 | SS.push_back( "The number is 20" ); |
13 | SS.push_back( "The number is 30" ); |
15 | cout << "Loop by index:" << endl; |
18 | for (ii=0; ii < SS.size(); ii++) |
20 | cout << SS[ii] << endl; |
23 | cout << endl << "Constant Iterator:" << endl; |
25 | vector<string>::const_iterator cii; |
26 | for (cii=SS.begin(); cii!=SS.end(); cii++) |
31 | cout << endl << "Reverse Iterator:" << endl; |
33 | vector<string>::reverse_iterator rii; |
34 | for (rii=SS.rbegin(); rii!=SS.rend(); ++rii) |
39 | cout << endl << "Sample Output:" << endl; |
41 | cout << SS.size() << endl; |
42 | cout << SS[2] << endl; |
45 | cout << SS[2] << endl; |
|
Compile: g++ exampleVector.cpp
Run: ./a.out
Output:
Loop by index:
The number is 10
The number is 20
The number is 30
Constant Iterator:
The number is 10
The number is 20
The number is 30
Reverse Iterator:
The number is 30
The number is 20
The number is 10
Sample Output:
3
The number is 30
The number is 10
Two / Three / Multi Dimensioned arrays using vector:
A two dimensional array is a vector of vectors. The vector contructor can initialize the length of the array and set the initial value.
- Example of a vector of vectors to represent a two dimensional array:
09 | vector< vector< int > > vI2Matrix(3, vector< int >(2,0)); |
18 | cout << "Loop by index:" << endl; |
21 | for (ii=0; ii < 3; ii++) |
23 | for (jj=0; jj < 2; jj++) |
25 | cout << vI2Matrix[ii][jj] << endl; |
|
Compile: g++ exampleVector2.cpp
Run: ./a.out
Loop by index:
0
1
10
11
20
21
A three dimensional vector would be declared as:
09 | vector< int > vI1Matrix(3,0); |
13 | vector< vector< int > > vI2Matrix(4, vI1Matrix); |
16 | vector< vector< vector< int > > > vI3Matrix(5, vI2Matrix); |
|
or declare all in one statement:
08 | vector< vector< vector< int > > > vI3Matrix(2, vector< vector< int > > (3, vector< int >(4,0)) ); |
10 | for ( int kk=0; kk<4; kk++) |
12 | for ( int jj=0; jj<3; jj++) |
14 | for ( int ii=0; ii<2; ii++) |
16 | cout << vI3Matrix[ii][jj][kk] << endl; |
|
Using an iterator:
- Example of iterators used with a two dimensional vector.
08 | vector< vector< int > > vI2Matrix; |
10 | vector< vector< int > >::iterator iter_ii; |
11 | vector< int >::iterator iter_jj; |
20 | vI2Matrix.push_back(A); |
21 | vI2Matrix.push_back(B); |
23 | cout << endl << "Using Iterator:" << endl; |
25 | for (iter_ii=vI2Matrix.begin(); iter_ii!=vI2Matrix.end(); iter_ii++) |
27 | for (iter_jj=(*iter_ii).begin(); iter_jj!=(*iter_ii).end(); iter_jj++) |
29 | cout << *iter_jj << endl; |
|
Compile: g++ exampleVector2.cpp
Run: ./a.out
Using Iterator:
10
20
30
100
200
300
[Potential Pitfall]: Note that "end()" points to a position after the last element and thus can NOT be used to point to the last element.
iter_jj = SS.end();
cout << *iter_jj << endl;
This will result in a "Segmentation fault" error.