Vector in C++

In C++, a vector is a dynamic array from the Standard Template Library (STL) that can automatically resize itself as elements are added or removed. Vectors provide efficient, contiguous storage for elements and support random access. They offer a variety of built-in functions for manipulation and iteration, making them a widely used data structure for storing and managing collections of data. Vectors are versatile and offer many of the benefits of arrays with the added advantage of automatic resizing, simplifying memory management in C++ programs.

Need for Vectors

Vectors in C++ are needed for several reasons. They provide dynamic array-like storage with automatic resizing, allowing for the efficient addition and removal of elements, which is not possible with standard arrays. Vectors also offer the ability to store and manage collections of data in a contiguous and memory-efficient manner, while providing various built-in functions for easy manipulation and iteration. Their dynamic nature, along with bounds checking, ensures safety and flexibility in handling data, making vectors a crucial tool for managing and organizing dynamic collections in C++ programs.

Example | C++ Vector
#include <iostream> #include <vector> int main() { // Create an empty vector of integers std::vector<int> myVector; // Add elements to the vector myVector.push_back(1); myVector.push_back(2); myVector.push_back(3); // Access and print elements std::cout << "Vector elements: "; for (int element : myVector) { std::cout << element << " "; } std::cout << std::endl; return 0; }

In this example, we include the <vector> header and create an empty vector of integers (std::vector <int> ). We then use the push_back function to add elements (1, 2, and 3) to the vector. Finally, we iterate through the vector and print its elements.

Basic Vector Operations

Here are the basic vector operations in C++ with examples:

Adding Elements to a Vector

You can add elements to a vector using the push_back() function or by specifying the element during vector initialization.

#include <iostream> #include <vector> int main() { // Creating a vector and adding elements std::vector<int> myVector; myVector.push_back(1); myVector.push_back(2); myVector.push_back(3); // Accessing and printing the elements for (int element : myVector) { std::cout << element << " "; } std::cout << std::endl; return 0; }

Accessing Elements in a Vector

You can access elements using the subscript ([]) operator or the at() function.

// Accessing elements int firstElement = myVector[0]; // Access the first element int secondElement = myVector.at(1); // Access the second element

Changing Elements in a Vector

You can modify elements by assigning new values using the subscript operator or the at() function.

// Modifying elements myVector[1] = 42; // Change the second element myVector.at(2) = 100; // Change the third element

Removing Elements from a Vector

You can remove elements using the pop_back() function to remove the last element or the erase() function to remove a specific element by its iterator.

// Removing elements myVector.pop_back(); // Remove the last element myVector.erase(myVector.begin() + 1); // Remove the second element // Accessing and printing the modified vector for (int element : myVector) { std::cout << element << " "; } std::cout << std::endl;

Functions in Vector

Here are some common functions, along with examples:

  1. push_back(): Adds an element to the end of the vector.
std::vector<int> numbers; numbers.push_back(1); numbers.push_back(2);
  1. pop_back(): Removes the last element from the vector.
numbers.pop_back(); // Removes the last element (2)
  1. size(): Returns the number of elements in the vector.
int count = numbers.size(); // Returns 1
  1. empty(): Checks if the vector is empty and returns a boolean value.
if (numbers.empty()) { // Vector is empty }
  1. clear(): Removes all elements from the vector, leaving it empty.
numbers.clear(); // Removes all elements
  1. insert(): Inserts elements at a specific position in the vector.
numbers.insert(numbers.begin() + 1, 5); // Inserts 5 at the second position
  1. erase(): Removes elements at a specific position or within a range.
numbers.erase(numbers.begin() + 1); // Removes the element at the second position
  1. front(): Returns a reference to the first element.
int first = numbers.front(); // Returns 1
  1. back(): Returns a reference to the last element.
int last = numbers.back(); // Returns 1
  1. resize(): Changes the size of the vector, either by trimming or padding with default values.
numbers.resize(3); // Resizes the vector to 3 elements
  1. swap(): Swaps the contents of two vectors.
std::vector<int> other = {10, 20}; numbers.swap(other); // Swaps the contents of 'numbers' and 'other'

Difference between Vector and Array in C++

Vectors and arrays in C++ are both used for storing collections of data, but they have fundamental differences. Arrays have a fixed size defined at compile time, and their size cannot be changed during runtime, leading to potential buffer overflows or underutilized memory. Vectors, on the other hand, are dynamic arrays from the C++ Standard Library (STL) that can grow or shrink dynamically, providing automatic memory management, resizing, and safe element access. Vectors offer flexibility and safety, making them a preferred choice for most scenarios, while arrays are used when a fixed, unchanging size is required, such as when defining simple, fixed-size data structures.

Conclusion

C++ vector is a dynamic array from the Standard Template Library (STL) that can automatically resize itself as elements are added or removed, providing flexibility and memory management. Vectors offer a wide range of built-in functions for efficient element access, manipulation, and iteration, making them a versatile and commonly used data structure for storing and managing collections of data in C++ programs.