Vector in C++ Standard Template Library (STL) with Example

What is a C++ Vector?

A C++ Vector is a dynamic array capable of resizing itself automatically. The resizing occurs after an element has been added or deleted from the vector. The storage is handled automatically by the container. The elements of a vector are stored in contiguous storage. This allows C++ programmers to access and traverse the vector elements using iterators.

The insertion of new data to a vector is done at its end. This takes a differential time. The removal of an element from a vector takes constant time. The reason is that there is no need to resize the vector. Insertion or deletion of an element at the beginning of the vector takes linear time.

When to Use a Vector?

A C++ vector should be used under the following circumstances:

  • When dealing with data elements that change consistently.
  • If the size of the data is not known before beginning, the vector won’t require you to set the maximum size of the container.

How to Initialize Vectors in C++

The syntax of vectors in C++ is:

vector <data-type> name (items)
  • As shown above, we begin with the vector keyword.
  • The data-type is the data type of the elements to be stored in the vector.
  • The name is the name of the vector or the data elements.
  • The items denote the number of elements for the vector’s data. This parameter is optional.

Iterators

The purpose of iterators is to help us access the elements that are stored in a vector. It’s an object that works like a pointer. Here are the common iterators supported by C++ vectors:

  • vector:: begin(): it gives an iterator that points to the first element of the vector.
  • vector:: end(): it gives an iterator that points to the past-the-end element of the vector.
  • vector::cbegin(): it’s the same as vector::begin(), but it doesn’t have the ability to modify elements.
  • vector::cend(): it’s the same as vector::end() but can’t modify vector elements.

Modifiers

Modifiers are used for changing the meaning of the specified data type. Here are the common modifiers in C++:

  • vector::push_back(): This modifier pushes the elements from the back.
  • vector::insert(): For inserting new items to a vector at a specified location.
  • vector::pop_back(): This modifier removes the vector elements from the back.
  • vector::erase(): It is used for removing a range of elements from the specified location.
  • vector::clear(): It removes all the vector elements.

Example 1

#include <iostream> 
#include <vector> 

using namespace std;
int main()
{
	vector<int> nums;

	for (int a = 1; a <= 5; a++)

		nums.push_back(a);

	cout << "Output from begin and end: ";

	for (auto a = nums.begin(); a != nums.end(); ++a)

		cout << *a << " ";

	cout << "\nOutput from cbegin and cend: ";

	for (auto a = nums.cbegin(); a != nums.cend(); ++a)

		cout << *a << " ";

	return 0;
}

Output:

Modifiers

Here is a screenshot of the code:

Modifiers

Code Explanation:

  1. Include the iostream header file in our code. It will allow us to read from and write to the console.
  2. Include the vector header file in our code. It will allow us to work with vectors in C++.
  3. Include the std namespace so as to use its classes and functions without calling it.
  4. Call the main() function inside which the logic of the program should be added.
  5. The { marks the start of the body of the main() function.
  6. Declare a vector named nums to store a set of integers.
  7. Create a for loop to help us iterate over the vector. The variable will help us iterate over the vector elements, from 1st to 5th elements.
  8. Push elements into the vector num from the back. For each iteration, this will add the current value of variable a into the vector, which is 1 to 5.
  9. Print some text on the console
  10. Use an iterator variable a to iterate over the elements of vector nums from the beginning to the past-the-end element. Note we are using vector::begin() and vector::end() iterators.
  11. Print the values pointed to by iterator variable an on the console for each iteration.
  12. Print some text on the console. The \n is a new line character, moving the cursor to the new line to print from there.
  13. Use an iterator variable to iterate over the elements of vector nums from the beginning to the past-the-end element. Note we are using vector::cbegin() and vector::cend() iterators.
  14. Print the values pointed to by iterator variable a on the console for each iteration.
  15. The main function should return a value if the program runs successfully.
  16. End of the body of the main() function.

Example 2

#include <iostream>
#include <vector> 

using namespace std;
int main()
{
	vector<int> nums;
	
	nums.assign(5, 1);

	cout << "Vector contents: ";
	for (int a = 0; a < nums.size(); a++)
		cout << nums[a] << " ";

	nums.push_back(2);
	int n = nums.size();
	cout << "\nLast element: " << nums[n - 1];

	nums.pop_back();

	cout << "\nVector contents: ";
	for (int a = 0; a < nums.size(); a++)
		cout << nums[a] << " ";

	nums.insert(nums.begin(), 7);

	cout << "\nFirst element: " << nums[0];
	
	nums.clear();
	cout << "\nSize after clear(): " << nums.size();			
}

Output:

Modifiers

Here is a screenshot of the code:

Modifiers

Code Explanation:

  1. Include the iostream header file in our code to use its functions.
  2. Include the vector header file in our code to use its functions.
  3. Include the std namespace to use its classes without calling it.
  4. Call the main() function. The program logic should be added inside its body.
  5. The start of the body of the main() function.
  6. Declare a vector named nums to store some integer values.
  7. Store 5 elements in the vector nums. Each with a value of 1.
  8. Print some text on the console
  9. Use an iterator variable a to iterate over the elements of vector nums.
  10. Print the values of vector nums on the console for each iteration.
  11. Add the value 2 to the end of the vector nums.
  12. Declare an integer variable n to store the size of the vector nums.
  13. Print the last value of vector nums alongside other text. It should return a 2.
  14. Remove the last element from the vector nums. The 2 will be removed.
  15. Print text on the console. The \n moves the cursor to the new line to print the text there.
  16. Use an iterator variable a to iterate over the elements of vector nums.
  17. Print the values of vector nums on the console for each iteration.
  18. Insert the value 7 to the beginning of the vector nums.
  19. Print the first value of vector nums alongside other text. It should return 7.
  20. Delete all elements from the vector nums.
  21. Print the size of the vector num alongside other text after clearing all contents. It should return 0.
  22. End of the body of the main() function.

Capacity

Use the following functions to determine the capacity of a vector:

  • Size() –It returns the number of items in a vector.
  • Max_size() -It returns the highest number of items a vector can store.
  • Capacity () –It returns the amount of storage space allocated to a vector.
  • Resize () –It resizes the container to contain n items. If the vector’s current size is greater than n, the back items will be removed from the vector. If the vector’s current size is smaller than n, extra items will be added to the back of the vector.
  • Empty () –it returns true if a vector is empty. Else, it returns false.

Example 3

#include <iostream> 
#include <vector> 
using namespace std;
int main() {
	vector<int> vector1;
	for (int x = 1; x <= 10; x++)
		vector1.push_back(x);
	cout << "Vector size: " << vector1.size()<< endl;
	cout << "Vector capacity: " << vector1.capacity() << endl;
	cout << "Maximum size of vector: " << vector1.max_size()<< endl;
	vector1.resize(5);
	cout << "Vector size after resizing: " << vector1.size() << endl;
	if (vector1.empty() == false)
		cout << "Vector is not empty"<<endl;
	else
		cout << "Vector is empty"<<endl;
	return 0;
}

Output:

Capacity

Here is a screenshot of the code:

Capacity

Code Explanation:

  1. Include the iostream header file in our code to use its function.
  2. Include the vector header file in our code to use its functions.
  3. Include the std namespace in our code to use its classes without calling it.
  4. Call the main() function. The program logic should be added within the body of this function.
  5. Create a vector named vector1 to store integers.
  6. Use a for loop to create variable x with values from 1 to 10.
  7. Push the values of variable x into the vector.
  8. Print the size of the vector alongside other text on the console.
  9. Print the capacity of the vector alongside other text on the console.
  10. Print the maximum number of items the vector can hold alongside other text on the console.
  11. Resize the vector to hold only 5 elements.
  12. Print the new size of the vector alongside other text.
  13. Check whether the vector is not empty.
  14. Print text on the console if the vector is not empty.
  15. Use an else statement to state what to do if the vector is empty.
  16. Text to print on the console if the vector is empty.
  17. The program must return value upon successful completion.
  18. End of the main() function body.

Summary

  • A C++ vector is a dynamic array capable of automatically resizing itself when an element is added or deleted from it.
  • The storage for a vector is handled automatically by the container.
  • The elements of a vector are stored in contiguous storage in order to be accessed then traversed using iterators.
  • The insertion of new data into a vector is done at its end.
  • The insertion of data into a vector takes a differential time.
  • The removal of an element from a vector takes constant time.
  • Insertion or deletion of an element at the beginning takes linear time.
  • Vectors should be used when dealing with data elements that change consistently.
  • Also, you can use vectors if the size of the data is not known before beginning.