Home C++ C++ Standard Template Library (STL) vector tutorial

C++ Standard Template Library (STL) vector tutorial

The vector in the C++ Standard Template Library (STL) is a dynamic array that can grow or shrink in size.

It provides random access to elements, supports efficient insertion and deletion at the end, and is one of the most commonly used containers in C++ due to its versatility.

Key Features of vector

  1. Dynamic Size: Can grow or shrink as elements are added or removed.
  2. Random Access: Elements can be accessed directly by their index.
  3. Efficient Operations: Efficient for insertion and deletion at the end.

Basic Syntax

#include <vector>
using namespace std;

vector<Type> v;

Let’s explore the vector with examples demonstrating common operations.

1. Initializing and Adding Elements

You can initialize a vector with values and add elements using the push_back function.

#include <iostream>
#include <vector>
using namespace std;

int main() {
    // Initialize an empty vector
    vector<int> v;

    // Add elements using push_back
    v.push_back(10);
    v.push_back(20);
    v.push_back(30);

    // Display elements
    cout << "Elements in the vector: ";
    for (int i = 0; i < v.size(); i++) {
        cout << v[i] << " ";
    }
    cout << endl;

    return 0;
}

Output:

Elements in the vector: 10 20 30 

2. Accessing Elements

Elements in a vector can be accessed using the [] operator or the at function. Both provide random access by index.

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> v = {10, 20, 30, 40};

    // Access elements using []
    cout << "Element at index 1: " << v[1] << endl;

    // Access elements using at()
    cout << "Element at index 3: " << v.at(3) << endl;

    return 0;
}

Output:

Element at index 1: 20
Element at index 3: 40

3. Modifying Elements

You can modify elements in a vector using the [] operator or at function.

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> v = {10, 20, 30};

    // Modify elements
    v[1] = 25;
    v.at(2) = 35;

    // Display modified vector
    cout << "Modified elements: ";
    for (int val : v) {
        cout << val << " ";
    }
    cout << endl;

    return 0;
}

Output:

Modified elements: 10 25 35 

4. Removing Elements

You can remove elements from a vector using pop_back to remove the last element, or erase to remove specific elements.

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> v = {10, 20, 30, 40};

    // Remove the last element
    v.pop_back();

    // Remove element at specific position
    v.erase(v.begin() + 1); // Removes the element at index 1

    // Display remaining elements
    cout << "Elements after removal: ";
    for (int val : v) {
        cout << val << " ";
    }
    cout << endl;

    return 0;
}

Output:

Elements after removal: 10 30 

5. Checking if the Vector is Empty

The empty function checks if the vector has any elements, returning true if it’s empty and false otherwise.

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> v;

    // Check if the vector is empty
    if (v.empty()) {
        cout << "The vector is empty." << endl;
    }

    // Add an element and check again
    v.push_back(5);
    if (!v.empty()) {
        cout << "The vector is not empty." << endl;
    }

    return 0;
}

Output:

The vector is empty.
The vector is not empty.

6. Getting the Size of the Vector

Use the size function to get the number of elements in the vector.

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> v = {10, 20, 30};

    // Display the size of the vector
    cout << "Size of the vector: " << v.size() << endl;

    return 0;
}

Output:

Size of the vector: 3

7. Using vector with Custom Data Types

You can store custom objects in a vector as long as they have a valid copy constructor and assignment operator.

#include <iostream>
#include <vector>
#include <string>
using namespace std;

// Custom structure for storing person information
struct Person {
    string name;
    int age;

    Person(string n, int a) : name(n), age(a) {}
};

int main() {
    vector<Person> v;

    // Insert custom objects
    v.push_back(Person("Alice", 25));
    v.push_back(Person("Bob", 30));

    // Access and display elements
    cout << "People in the vector:" << endl;
    for (const auto &person : v) {
        cout << person.name << " (" << person.age << ")" << endl;
    }

    return 0;
}

Output:

People in the vector:
Alice (25)
Bob (30)

8. Clearing the Vector

The clear function removes all elements from the vector, making it empty.

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> v = {10, 20, 30};

    cout << "Size before clear: " << v.size() << endl;

    // Clear the vector
    v.clear();

    cout << "Size after clear: " << v.size() << endl;

    return 0;
}

Output:

Size before clear: 3
Size after clear: 0

9. Initializing a Vector with a Specific Size and Value

You can initialize a vector with a specified size and value using the constructor.

#include <iostream>
#include <vector>
using namespace std;

int main() {
    // Initialize a vector with 5 elements, all set to 10
    vector<int> v(5, 10);

    // Display elements
    cout << "Elements in the vector: ";
    for (int val : v) {
        cout << val << " ";
    }
    cout << endl;

    return 0;
}

Output:

Elements in the vector: 10 10 10 10 10 

10. Using reserve to Optimize Performance

The reserve function can pre-allocate memory for a vector to avoid repeated memory allocations.

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> v;

    // Reserve memory for 100 elements
    v.reserve(100);

    // Add elements to the vector
    for (int i = 0; i < 10; i++) {
        v.push_back(i);
    }

    cout << "Size of vector: " << v.size() << endl;
    cout << "Capacity of vector: " << v.capacity() << endl;

    return 0;
}

Output:

Size of vector: 10
Capacity of vector: 100

Summary Table of vector Operations

Operation Code Example Description
Initialize vector<int> v = {10, 20}; Creates a vector with initial values
Add Element v.push_back(10); Adds an element to the end of the vector
Access Element v[i] or v.at(i); Accesses an element at a specific index
Modify Element v[i] = 20; Modifies an element at a specific index
Remove Last Element v.pop_back(); Removes the last element
Remove Specific Element v.erase(v.begin() + i); Removes element at a specific position
Check if Empty v.empty(); Checks if the vector is empty
Get Size v.size(); Returns the number of elements in the vector
Reserve Capacity v.reserve(100); Reserves space for a specific number of elements
Clear v.clear(); Removes all elements from the vector
Initialize with Size vector<int> v(5, 10); Creates a vector of size 5, all elements set to 10

Complete Example

This example demonstrates initializing a vector, adding and removing elements, checking the size, and clearing the vector.

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> v;

    // Adding elements
    v.push_back(5);
    v.push_back(10);
    v.push_back(15);

    // Display the size of the vector
    cout << "Size of vector: " << v.size() << endl;

    // Display all elements in the vector
    cout << "Elements in the vector: ";
    for (int val : v) {
        cout << val << " ";
    }
    cout << endl;

    // Remove an element
    v.pop_back();
    cout << "Elements after removing last element: ";
    for (int val : v) {
        cout << val << " ";
    }
    cout << endl;

    // Clear the vector
    v.clear();
    cout << "Is the vector empty? " << (v.empty() ? "Yes" : "No") << endl;

    return 0;
}

Sample Output:

Size of vector: 3
Elements in the vector: 5 10 15 
Elements after removing last element: 5 10 
Is the vector empty? Yes

Key Takeaways

  • vector in C++ is a dynamic array that supports random access and efficient operations at the end.
  • Key operations include push_back, pop_back, size, empty, and reserve.
  • vector is highly versatile, making it ideal for storing sequences of elements that can grow or shrink dynamically.

 

You may also like