Vectors

Similar to arrays, but dynamically resizes as the program requires.

 

Elements start from 0.

 

Declared by using the vector keyword, then enclosing the data type with <angle brackets>, followed by the preferred identifier and size as follows:

 

vector <data-type> vecotor-name ( size ) ;

 

Or with an initial value: vector <data-type> vecotor-name ( size, initial-value ) ;

 

Requires the vector library and therefore must use the preprocessor directive: #include <vector>

 

This library also allows a number of vector functions.

 

To use a vector functions simply append the function required with the dot operator e.g. to find out the number of elements for a vector initialised like so: vector <char> cactus(5, 27) ;

 

cout << cactus.size() ; // would return a value of 5

 

#include <vector>
#include <iostream>
using namespace std ;

int main()
{
	vector <int> myVec(7,42) ; //initialise the vector

	cout << "myVec was initialised with " << myVec.size() << " elements, " \
		  "the first being: " << myVec.at(0) << \
		  ", and is therefore " << (myVec.empty() ? "Empty." : "Populated.") << endl << endl ;

	cout << "Adding another element to the end " ;
	myVec.push_back( 63 ) ; // Add an element.
	cout << "has increased the size of the vector to " << myVec.size() << " elements, " \
			"and we can see that " << myVec.back() << " is the last value!" << endl << endl ;

	cout << "Let's remove that last element, " ;
	myVec.pop_back() ; // Remove final element
	cout << "which reduces the vector size to: " << myVec.size() << \
			" and we can once again see that the final element is: " << myVec.back() << endl << endl ;

	cout << "OK, enough of this myVec, let's clear it out and move on! " ;
	myVec.clear() ; // Remove all elements.
	cout << "myVec is now: " << myVec.size() << endl ;

return 0;
}

Compile & Run:

myVec was initialised with 7 elements, the first being: 42, and is therefore Populated. 

 

Adding another element to the end has increased the size of the vector to 8 elements, and we can see that 63 is the last value!

 

Let's remove that last element, which reduces the vector size to: 7 and we can once again see that the final element is: 42

 

OK, enough of this myVec, let's clear it out and move on! myVec is now: 0

 

myVec.at(pos) Returns the value at pos
myVec.back() Returns the value in the final element
myVec.clean() Removes all elements
myVec.empty() Returns TRUE (1) if empty, or FALSE (0) otherwise
myVec.front() Returns the value in the first element
myVec.pop_back() Removes the final element
myVec.push_back(value) Adds the specified value at the end of the vector
myVec.size() Returns the number of elements  in the vector

Leave a Reply