The <vector> container is one of the most commonly used containers in C++ due to its dynamic array capabilities. It provides a flexible way to store elements that can grow and shrink as needed, making it ideal for applications where the number of elements isn't known at compile time.
In this tutorial, we'll explore all the essential methods provided by the <vector> container, including push_back, pop_back, insert, erase, resize, reserve, capacity, shrink_to_fit, data, and emplace. Understanding these methods will help you effectively manage dynamic arrays in your C++ programs.
The <vector> container is part of the Standard Template Library (STL) and provides a dynamic array that can resize itself automatically when elements are added or removed. This makes it a versatile choice for various programming tasks, from simple data storage to complex algorithms.
In this tutorial, we'll cover each method in detail, providing clear explanations, code examples, and expected outputs. By the end of this guide, you'll have a solid understanding of how to use <vector> effectively in your C++ projects.
push_backThe push_back method adds an element to the end of the vector.
Example:
1#include <iostream>2#include <vector>34int main() {5std::vector<int> vec;6vec.push_back(10);7vec.push_back(20);89for (int num : vec) {10std::cout << num << " ";11}1213return 0;14}
Output:
10 20
pop_backThe pop_back method removes the last element from the vector.
Example:
1#include <iostream>2#include <vector>34int main() {5std::vector<int> vec = {10, 20, 30};6vec.pop_back();78for (int num : vec) {9std::cout << num << " ";10}1112return 0;13}
Output:
10 20
insertThe insert method adds an element at a specified position in the vector.
Example:
1#include <iostream>2#include <vector>34int main() {5std::vector<int> vec = {10, 20, 30};6auto it = vec.insert(vec.begin() + 1, 15);78for (int num : vec) {9std::cout << num << " ";10}1112return 0;13}
Output:
10 15 20 30
eraseThe erase method removes an element from a specified position in the vector.
Example:
1#include <iostream>2#include <vector>34int main() {5std::vector<int> vec = {10, 20, 30};6auto it = vec.erase(vec.begin() + 1);78for (int num : vec) {9std::cout << num << " ";10}1112return 0;13}
Output:
10 30
resizeThe resize method changes the size of the vector to a specified number of elements.
Example:
1#include <iostream>2#include <vector>34int main() {5std::vector<int> vec = {10, 20, 30};6vec.resize(2);78for (int num : vec) {9std::cout << num << " ";10}1112return 0;13}
Output:
10 20
reserveThe reserve method allocates enough memory to hold a specified number of elements, without changing the size of the vector.
Example:
1#include <iostream>2#include <vector>34int main() {5std::vector<int> vec;6vec.reserve(10);78std::cout << "Capacity: " << vec.capacity() << std::endl;910return 0;11}
Output:
Capacity: 10
capacityThe capacity method returns the maximum number of elements that the vector can hold without needing to reallocate memory.
Example:
1#include <iostream>2#include <vector>34int main() {5std::vector<int> vec = {10, 20, 30};6std::cout << "Capacity: " << vec.capacity() << std::endl;78return 0;9}
Output:
Capacity: 4
shrink_to_fitThe shrink_to_fit method reduces the capacity of the vector to fit its size, freeing up memory.
Example:
1#include <iostream>2#include <vector>34int main() {5std::vector<int> vec = {10, 20, 30};6vec.reserve(10);7std::cout << "Capacity before shrink_to_fit: " << vec.capacity() << std::endl;89vec.shrink_to_fit();10std::cout << "Capacity after shrink_to_fit: " << vec.capacity() << std::endl;1112return 0;13}
Output:
Capacity before shrink_to_fit: 10 Capacity after shrink_to_fit: 3
dataThe data method returns a pointer to the underlying array used by the vector.
Example:
1#include <iostream>2#include <vector>34int main() {5std::vector<int> vec = {10, 20, 30};6int* arr = vec.data();78for (size_t i = 0; i < vec.size(); ++i) {9std::cout << arr[i] << " ";10}1112return 0;13}
Output:
10 20 30
emplaceThe emplace method constructs an element in-place at a specified position, avoiding unnecessary copying or moving of elements.
Example:
1#include <iostream>2#include <vector>3#include <string>45int main() {6std::vector<std::string> vec;7vec.emplace_back("Hello");8vec.emplace_back("World");910for (const auto& str : vec) {11std::cout << str << " ";12}1314return 0;15}
Output:
Hello World
Let's put all these methods together in a practical example. We'll create a program that manages a list of integers, allowing users to add, remove, and display elements.
1#include <iostream>2#include <vector>34int main() {5std::vector<int> vec;6int choice, num;78while (true) {9std::cout << "1. Add element102. Remove last element113. Display elements124. Exit13";14std::cout << "Enter your choice: ";15std::cin >> choice;1617switch (choice) {18case 1:19std::cout << "Enter an integer to add: ";20std::cin >> num;21vec.push_back(num);22break;23case 2:24if (!vec.empty()) {25vec.pop_back();26} else {27std::cout << "Vector is empty!" << std::endl;28}29break;30case 3:31for (int n : vec) {32std::cout << n << " ";33}34std::cout << std::endl;35break;36case 4:37return 0;38default:39std::cout << "Invalid choice!" << std::endl;40}41}4243return 0;44}
| Method | Description |
|---|---|
push_back | Adds an element to the end of the vector. |
pop_back | Removes the last element from the vector. |
insert | Inserts an element at a specified position in the vector. |
erase | Removes an element from a specified position in the vector. |
resize | Changes the size of the vector to a specified number of elements. |
reserve | Allocates enough memory to hold a specified number of elements. |
capacity | Returns the maximum number of elements that the vector can hold without reallocating. |
shrink_to_fit | Reduces the capacity of the vector to fit its size, freeing up memory. |
data | Returns a pointer to the underlying array used by the vector. |
emplace | Constructs an element in-place at a specified position, avoiding unnecessary copying or moving. |
Now that you have a comprehensive understanding of the <vector> container and its methods, you can move on to learning about other STL containers and algorithms. The next topic is "<algorithm> Reference," where we'll explore various algorithms available in the C++ Standard Library and how to use them effectively.
Stay tuned for more tutorials and happy coding!