As you know, in C++, the size of an array is fixed at the compile time. This can be very restrictive sometimes, because the size of the array cannot be adjusted at run time to accommodate changing program conditions. A vector solves this problem by allocating memory as needed. Remember, you can still use the standard array subscript notation to access its elements.
The following code fragments shows you how to declare vectors:
vector<int> iv; // create zero-length int vector vector<char>cv(5); // create 5-element char vector vector<char>cv(5, 'x'); // initialize a 5-element char vector
size(): This function returns the current size of the vector. This function is quite useful because which vector can grow as needed, this function enables you to determine the size of the vector at runtime.
begin(): This function returns an iterator (a pointer) to the start of the vector.
end(): This function returns an iterator to the end of the vector.
push_back(): This function puts a value onto the end of the vector. If necessary, the vector is increased in length to accommodate the new element.
insert(): This function inserts elements in the middle of the vector.
erase(): This function erases element from the vector.
The following sample program demonstrates the use of the above functions:
// Demonstrate vector member functions #include <iostream> #include <vector> //must be included using namespace std; int main() { vector<char> v; // declare a char vector of zero length int i; for(i = 0; i < 10; i++) v.push_back('A' + i); // insert values A, B, C, ... //display content of vector: cout << "Size = " << v.size() << endl; cout << "Original contents: \n"; for(i = 0; i < v.size(); i++) cout << v[i] << " " ; cout << endl << endl; //declare an iterator: vector<char>::iterator p = v.begin(); p += 2; // point to the third element // insert 10 X's into v, starting from p -- the third element v.insert(p, 10, 'X'); // display contents after insertion cout << "Size after insertion = " << v.size()<<endl; cout << "contents after insert: " << endl; for(i = 0; i < v.size(); i++) cout << v[i] << " "; cout << endl <<endl; //remove those elements: p = v.begin(); // set the iterator to beginning again p +=2; // point to the third element v.erase(p, p+10); // remove next ten elements //display contents after deletion cout << "Size after erase = " << v.size() << endl; cout << "Contents after erase:\n"; for(i = 0; i < v.size(); i++) cout << v[i] << " "; cout << endl <<endl; return 0; }The output is as follows:
Size = 10 Original contents: A B C D E F G H I J Size after insert = 20 Contents after insert: A B X X X X X X X X X X C D E F G H I J Size after erase = 10 Contents after erase: A B C D E F G H I
#include <iostream> #include <vector> using namespace std;
|
|
|