Vector Basics

Basic Vector Operations in C++

BeginnerTopic: STL Containers Programs
Back

C++ Vector Basics Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#include <iostream>
#include <vector>
using namespace std;

int main() {
    // Create vector
    vector<int> vec;
    
    // Add elements
    vec.push_back(10);
    vec.push_back(20);
    vec.push_back(30);
    vec.push_back(40);
    vec.push_back(50);
    
    cout << "Vector elements: ";
    for (int i = 0; i < vec.size(); i++) {
        cout << vec[i] << " ";
    }
    cout << endl;
    
    // Access elements
    cout << "First element: " << vec.front() << endl;
    cout << "Last element: " << vec.back() << endl;
    cout << "Element at index 2: " << vec.at(2) << endl;
    
    // Size and capacity
    cout << "Size: " << vec.size() << endl;
    cout << "Capacity: " << vec.capacity() << endl;
    
    // Initialize vector with values
    vector<int> vec2 = {1, 2, 3, 4, 5};
    cout << "\nVector 2: ";
    for (int num : vec2) {
        cout << num << " ";
    }
    cout << endl;
    
    // Remove last element
    vec.pop_back();
    cout << "\nAfter pop_back: ";
    for (int num : vec) {
        cout << num << " ";
    }
    cout << endl;
    
    return 0;
}
Output
Vector elements: 10 20 30 40 50
First element: 10
Last element: 50
Element at index 2: 30
Size: 5
Capacity: 8

Vector 2: 1 2 3 4 5

After pop_back: 10 20 30 40

Understanding Vector Basics

Vector is a dynamic array that can resize automatically. It provides random access, efficient insertion/deletion at the end. Key operations: push_back(), pop_back(), size(), capacity(), front(), back(), at(). Vectors store elements contiguously in memory, making them cache-friendly. They automatically manage memory allocation.

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Table of Contents