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

⚡ Smart Summary

Vector in C++ is a dynamic array from the Standard Template Library that resizes itself automatically as elements are added or removed, storing items in contiguous memory so programmers can access and traverse them using iterators.

  • 📦 Dynamic array: A C++ vector grows or shrinks automatically, unlike a fixed-size static array.
  • 🧩 Header and syntax: Include the vector header, then declare vector<data-type> name to store typed elements.
  • 🧭 Iterators: begin(), end(), cbegin(), and cend() move across vector elements like pointers.
  • 🛠️ Modifiers: push_back(), insert(), pop_back(), erase(), and clear() change vector contents.
  • 📐 Capacity: size(), capacity(), max_size(), resize(), and empty() report or adjust storage.
  • 🤖 AI assistance: GitHub Copilot and similar AI assistants scaffold vector operations from a short comment.

C++ Vector STL

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.

Before writing code with vectors, it helps to know when they are the right container to reach for.

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 will not 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 data. This parameter is optional.

Once a vector exists, iterators give you a pointer-like way to move across its elements.

Iterators

The purpose of iterators is to help us access the elements that are stored in a vector. It is 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 is the same as vector::begin(), but it does not have the ability to modify elements.
  • vector::cend(): it is the same as vector::end() but cannot modify vector elements.

The following example populates a vector and then walks through it with both mutable and constant iterators.

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:

C++ vector iterators Example 1 output

Here is a screenshot of the code:

C++ vector iterators Example 1 code

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 a 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.

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.

The next example applies these modifiers in sequence to see how a vector changes.

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:

C++ vector modifiers Example 2 output

Here is a screenshot of the code:

C++ vector modifiers Example 2 code

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 current size is greater than n, the back items will be removed from the vector. If the vector 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.

This final example reports and adjusts the storage of a vector using the capacity functions above.

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:

C++ vector capacity Example 3 output

Here is a screenshot of the code:

C++ vector capacity Example 3 code

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.

FAQs

A vector is a dynamic array that resizes itself automatically and knows its own size, while a built-in array has a fixed length set at compile time. Vectors manage memory for you; raw arrays do not.

Use the subscript operator, such as nums[0], for fast direct access. The at() member function, like nums.at(0), does the same but throws an out_of_range exception when the index is invalid, making it safer.

Declare a vector whose elements are themselves vectors, for example vector<vector<int>> grid. You can size it with constructors or push_back rows. Each inner vector can grow independently, giving you a flexible, resizable matrix.

A vector stores elements in contiguous memory with fast random access, while a std::list is a doubly linked list with fast insertion or deletion anywhere but no direct indexing. Choose based on your access pattern.

Include the algorithm header and call std::sort with the begin and end iterators, as in sort(nums.begin(), nums.end()). Sorting is ascending by default; pass a custom comparator or greater<int>() to sort in descending order.

Yes. A vector is a template and can hold any type, including string, custom classes, and even other vectors. Declare the element type inside the angle brackets, such as vector<string> or vector<Employee>.

Yes. AI coding assistants turn a short prompt or comment into working vector code, including declaration, push_back loops, and iteration. Always review the suggested types, bounds, and capacity handling, since AI can miss project-specific requirements.

Yes. GitHub Copilot suggests vector declarations, push_back and insert calls, and iterator loops as you type. It handles repetitive boilerplate well, though you should still verify indices, resizing, and logic before compiling.

Summarize this post with: