Vectors in C++
Vectors are a dynamic array-like data structure that stores elements of the same data type in a contiguous fashion that can resize itself automatically unlike arrays which mean vectors can grow when an element is inserted or shrink when an element is deleted.
- Vectors are present in C++ Standard Template Library (STL).
- We have to #include <vector> header file in our C++ program to use vectors.
Syntax to declare a Vector
vector<data_type> vectorName;
Commonly used Vector Functions
- push_back() – It is used to insert the elements at the end of the vector.
- pop_back() – It is used to pop or remove elements from the end of the vector.
- clear() – It is used to remove all the elements of the vector.
- empty() – It is used to check if the vector is empty.
- at(i) – It is used to access the element at the specified index ‘i’.
- front() – It is used to access the first element of the vector.
- back() – It is used to access the last element of the vector.
- erase() – It is used to remove an element at a specified position.
Example
C++
#include <iostream> #include <vector> using namespace std; int main() { // Create an empty vector vector< int > numbers; // push_back() numbers.push_back(10); numbers.push_back(20); numbers.push_back(30); // Accessing elements using at() // Output: 10 cout << "Element at index 0: " << numbers.at(0) << endl; // Output: 20 cout << "Element at index 1: " << numbers.at(1) << endl; // front() and back() // Output: 10 cout << "First element: " << numbers.front() << endl; // Output: 30 cout << "Last element: " << numbers.back() << endl; // pop_back() // Remove the last element numbers.pop_back(); // erase() // Remove the element at index 1 numbers.erase(numbers.begin() + 1); // empty() if (numbers.empty()) { cout << "Vector is empty" << endl; } else { cout << "Vector is not empty" << endl; } // clear() // Remove all elements numbers.clear(); if (numbers.empty()) { cout << "Vector is empty" << endl; } else { cout << "Vector is not empty" << endl; } return 0; } |
Element at index 0: 10 Element at index 1: 20 First element: 10 Last element: 30 Vector is not empty Vector is empty
C++ Cheatsheet
This is a C++ programming cheat sheet. It is useful for beginners and intermediates looking to learn or revise the concepts of C++ programming. While learning a new language, it feels annoying to switch pages and find different websites for different concepts that are easily understandable. You can learn C++ concepts very easily using this cheat sheet.
C++ is a high-level programming language. It was developed in 1983 by Bjarne Stroustrup at Bell Labs. It is used for developing various applications.