Introduction
In this article, we will see C++ Vector with the help of examples. Vectors are used in C++ to hold components of related data types. Unlike arrays, however, the size of a vector can expand dynamically. That is, we may change the size of the vector during program execution to meet our needs.
Vectors are a kind of template in the C++ Standard Template Library (STL). We must include the vector header file in our application in order to use vectors.
#include <vector>
C++ Vector Declaration
Here’s how to declare a vector in C++ after we have included the vector in a header file.
std::vector<T> vector_name;
The vector’s type is specified by the type argument <T>. It might be any primitive data type, such as int, char, float, and so on. For an example:
vector<int> num;
In this case, num is the vector’s name. It’s worth noting that we didn’t specify the C++ vector size during the declaration. This is due to the fact that the size of a vector might grow dynamically, therefore it is unnecessary to specify it.
C++ Vector Initialization
There are different ways to initialize a vector in C++.
Method 01: [initializer list] Below code snippet will show you the C++ Vector example of initialization.
#include <iostream>
#include <vector>
using namespace std;
int main() {
// initializer list
vector<int> vect = {1, 2, 3, 4, 5};
cout << "vector = ";
// ranged loop
for (const int& i : vect) {
cout << i << " ";
}
return 0;
}
Output:
vector = 1 2 3 4 5
Method 02: [uniform initialization] Below code snippet will show you the C++ Vector example of initialization.
#include <iostream>
#include <vector>
using namespace std;
int main() {
// uniform initialization
vector<int> vect{1, 2, 3, 4, 5};
cout << "vector = ";
// ranged loop
for (const int& i : vect) {
cout << i << " ";
}
return 0;
}
Output:
vector = 1 2 3 4 5
Method 03:
#include <iostream>
#include <vector>
using namespace std;
int main() {
// method 3
vector<int> vect(5, 10);
cout << "vector = ";
// ranged loop
for (const int& i : vect) {
cout << i << " ";
}
return 0;
}
Output:
vector = 10 10 10 10 10
Basic C++ Vector Operations
The vector class has a number of methods for performing various operations on vectors. In this section, we will look at several commonly used vector operations.
- Add elements
- Access elements
- Change elements
- Remove elements
Operation 01: Add Element
The push_back() function is used to insert a single element into a vector. It adds a new element to the end of the vector.
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> num {1, 2, 3, 4, 5};
cout << "Initial Vector: ";
for (const int& i : num) {
cout << i << " ";
}
num.push_back(6);
num.push_back(7);
cout << "\nUpdated Vector: ";
for (const int& i : num) {
cout << i << " ";
}
return 0;
}
Output:
Initial Vector: 1 2 3 4 5 Updated Vector: 1 2 3 4 5 6 7
Note: We can also use the C++ Vector insert() and emplace() functions to add elements to a vector.
Operation 02: Access Elements
To access the vector items in C++, we utilize the index number. The at() function is used here to retrieve the element from the given index.
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> num {1, 2, 3, 4, 5};
cout << "Element at Index 4: " << num.at(4) << endl;
cout << "Element at Index 3: " << num.at(3) << endl;
cout << "Element at Index 2: " << num.at(2) << endl;
cout << "Element at Index 1: " << num.at(1) << endl;
cout << "Element at Index 0: " << num.at(0);
return 0;
}
Output:
Element at Index 4: 5 Element at Index 3: 4 Element at Index 2: 3 Element at Index 1: 2 Element at Index 0: 1
Operation 03: Change Elements
Using the same at() function, we may change an element in the vector.
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> num {1, 2, 3, 4, 5};
cout << "Initial Vector: ";
for (const int& i : num) {
cout << i << " ";
}
// change elements at indexes 0 and 3
num.at(0) = 5;
num.at(3) = 15;
cout << "\nUpdated Vector: ";
for (const int& i : num) {
cout << i << " ";
}
return 0;
}
Output:
Initial Vector: 1 2 3 4 5 Updated Vector: 5 2 3 15 5
Operation 04: Delete Elements
The C++ Vector pop_back() function is used to delete a single element from a vector.
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> num{1, 2, 3, 4, 5};
// initial vector
cout << "Initial Vector: ";
for (int i : num) {
cout << i << " ";
}
// remove the last element
num.pop_back();
// final vector
cout << "\nUpdated Vector: ";
for (int i : num) {
cout << i << " ";
}
return 0;
}
Output:
Initial Vector: 1 2 3 4 5 Updated Vector: 1 2 3 4
C++ Vector Iterator
Vector iterator is used to point to the memory address of a vector element. In certain aspects, they behave similarly to pointers in C++.
Syntax:
vector<T>::iterator iteratorName;
Initialize Vector Iterator
The begin() and end() functions can be used to initialize vector iterators.
begin() Function
The begin() function returns an iterator pointing to the vector’s first element.
vector<int> num = {1, 2, 3, 4, 5};
vector<int>::iterator iter;
// iter points to num[0]
iter = num.begin();
end() function
The end() function returns the theoretical element that follows the vector’s final member.
// iter points to the last element of num
iter = num.end() - 1;
Code Examples
Example 01:
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> num {1, 2, 3, 4, 5};
// declare iterator
vector<int>::iterator iter;
// initialize the iterator with the first element
iter = num.begin();
// print the vector element
cout << "num[0] = " << *iter << endl;
// iterator points to the 4th element
iter = num.begin() + 3;
cout << "num[3] = " << *iter << endl;
// iterator points to the last element
iter = num.end() - 1;
cout << "num[4] = " << *iter;
return 0;
}
Output:
num[0] = 1 num[3] = 4 num[4] = 5
Example 02: Iterate Through Vector Using Iterators
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> num {1, 2, 3, 4, 5};
// declare iterator
vector<int>::iterator iter;
// use iterator with for loop
for (iter = num.begin(); iter != num.end(); ++iter) {
cout << *iter << " ";
}
return 0;
}
Output:
1 2 3 4 5
C++ Vector Functions
The vector header file in C++ contains a number of functions that may be used to perform various operations on a vector.
Function | Description |
---|---|
size() | Returns the number of elements present in the vector |
clear() | Removes all the elements of the vector |
front() | Returns the first element of the vector |
back() | It returns the last element of the vector |
empty() | Returns 1 (true) if the vector is empty |
capacity() | Check the overall size of a vector |
FAQs
C++ Vector vs Array
- Vector is a sequential container, whereas Array is a lower-level data structure.
- A Vector is shipped in the form of a template class in C++ with a parent as a Collection class. Whereas an Array is the lower level data structure with its own specific properties.
- Vector is not index-base and has functions & constructors. Whereas Arrays are index-based data structures with the lowest address provided to the first element. And the highest address is provided to the last element in the array.
- A Vector is dynamic in nature, i.e. its size automatically increases with more element insertion. Whereas Arrays are a fixed-size structure, once initialized, cannot be reset.
- Vector is better for frequent insertion and deletion. Whereas Arrays are much better suited for frequent access of elements scenario.
C++ Vector vs List
- The items in the Vector are synchronized because they are kept in contiguous memory regions. But the elements in the List are store randomly and connect to one another by links (points), hence they are non-synchronize.
- When it comes to insertion and deletion, Lists outperform Vectors because insertion/ deletion at any position takes the same amount of time and follows the same procedure of swapping pointers. Whereas insertion/ deletion in Vectors at the last position is simple (by default, it inserts/ deletes elements at the last) but in the middle or beginning requires traversing the entire array. Inserting a new element, and shifting the rest of the elements.
- Because the memory of the Vector is pre-allocate. If the memory becomes insufficient during insertion, fresh contiguous memory must be allocate and the elements must be shift. However, there is no issue of memory insufficiency in the List because the memory is allocate dynamically.
- One of the most significant advantages of Vector is that it is thread-safe, whereas List in C++ is not.
Conclusion
That’s all for this article, if you have any confusion contact us through our website or email us at [email protected] or by using LinkedIn
Suggested Articles: