Vector is a template class and it allows programmers to create a dynamic array of elements of one type per instance.
Vector is conceptually same as arrays in C. However, vector size can expand to hold more elements and can shrink when fewer will suffice.
Note: Accessing members of vector or appending elements does not depend on vector size and takes fixed amount of time, however, locating a specific value element or inserting value element into vector takes the amount of time directly proportional to its location in vector.
//////////////////////////////////////////////////////////////////////
// Standard Template Library (STL)
//
// Vector Functions:
//
// vector::push_back - Appends (inserts) an element to the end of a
// vector, allocating memory for it if necessary.
//
// vector::pop_back - Erases the last element of the vector.
//
// vector::size - Returns number of elements in the vector.
//
//////////////////////////////////////////////////////////////////////
#include
#include <vector >
using namespace std ;
int main()
{
// Dynamically allocated vector begins with 0 elements.
vector<int>
// Add one element to the end of the vector, an int with the value 1.
// Allocate memory if necessary.
theVector.push_back(1) ;
// Add two more elements to the end of the vector.
// theVector will contain [ 1, 2, 3 ].
theVector.push_back(2) ;
theVector.push_back(3) ;
int tmp;
cout << "\n Enter new element on new line. press Ctrl +D to terminate " <
while (cin >> tmp)
theVector.push_back(tmp);
// Erase last element in the vector.
theVector.pop_back();
theVector.pop_back();
// Print contents of theVector.
cout << "theVector [" ;
for (int k =0; k < theVector.size(); k++)
cout <<" " << theVector[k];
cout << " ]" << endl ;
}
No comments:
Post a Comment