C++ Container Classes<vector>

Introduction

The C++ Standard Template Library (STL) is an important part of C++, providing a set of generic template classes and functions for handling data collections.<vector>It is a container class in the STL, used for storing arrays of dynamic size.

<vector>It is a sequence container that allows users to quickly add or remove elements at the end of the container. Compared with arrays,<vector>it provides more functionality, such as automatic resizing, random access, and so on.

Syntax

In C++, using<vector>Need to include the header file<<vector>>. The following is some basic syntax:

  • Declare avector:

    std::vector<int> myVector;
  • Add elements:

    myVector.push_back(10);
  • Access elements:

    int firstElement = myVector[0];
  • Get the number of elements:

    size_t size = myVector.size();
  • Clearvector:

    myVector.clear();

Declaration and initialization

<vector>The element type must be specified, and it can be initialized in multiple ways:

#include <iostream>
#include <vector>

int main() {
    std::vector<int> vec1;                  // 空的vector
    std::vector<int> vec2(5);               // 长度为5的vector,元素默认初始化
    std::vector<int> vec3(5, 10);           // 长度为5的vector,元素值为10
    std::vector<int> vec4 = {1, 2, 3, 4};   // 使用初始化列表初始化

    return 0;
}

Example

The following is a usage<vector>of a simple example, including the output results.

Example

#include <iostream>
#include <vector>

int main() {
    // Declare a vector that stores integers
    std::vector<int> numbers;

    // Add elements
    numbers.push_back(10);
    numbers.push_back(20);
    numbers.push_back(30);

    // Output the elements in the vector
    std::cout << "Vector contains: ";
    for (int i = 0; i < numbers.size(); ++i) {
        std::cout << numbers[i] << " ";
    }
    std::cout << std::endl;

    // Add more elements
    numbers.push_back(40);
    numbers.push_back(50);

    // Output the elements in the vector again
    std::cout << "After adding more elements, vector contains: ";
    for (int i = 0; i < numbers.size(); ++i) {
        std::cout << numbers[i] << " ";
    }
    std::cout << std::endl;

    // Access a specific element
    std::cout << "The first element is: " << numbers[0] << std::endl;

    // Clear the vector
    numbers.clear();

    // Check if the vector is empty
    if (numbers.empty()) {
        std::cout << "The vector is now empty." << std::endl;
    }

    return 0;
}

Output:

Vector contains: 10 20 30 
After adding more elements, vector contains: 10 20 30 40 50 
The first element is: 10 
The vector is now empty.

Common member functions

The following are<vector>Some commonly used member functions in:

Function Description
push_back(const T& val) Add an element at the end
pop_back() Delete the last element
at(size_t pos) Returns the element at the specified position, with bounds checking
operator[] Returns the element at the specified position, without bounds checking
front() Return the first element
back() Returns the last element
data() Returns a pointer to the underlying array
size() Returns the current number of elements
capacity() Returns the currently allocated capacity
reserve(size_t n) Reserve at leastnStorage space for elements
resize(size_t n) Resizes the number of elements ton
clear() Clear all elements
insert(iterator pos, val) Inserts an element at the specified position
erase(iterator pos) Deletes the element at the specified position
begin() / end() Return begin/end iterators

Example

1. Basic operations

Example

#include <iostream>
#include <vector>

int main() {
    std::vector<int> vec = {1, 2, 3, 4, 5};

    // Output all elements
    std::cout << "Vector elements: ";
    for (int i = 0; i < vec.size(); ++i) {
        std::cout << vec[i] << " ";
    }
    std::cout << std::endl;

    // Get the first and last elements
    std::cout << "First element: " << vec.front() << std::endl;
    std::cout << "Last element: " << vec.back() << std::endl;

    return 0;
}

2. Dynamically adding and removing elements

Example

#include <iostream>
#include <vector>

int main() {
    std::vector<int> vec;
    vec.push_back(10);
    vec.push_back(20);
    vec.push_back(30);

    std::cout << "Vector size: " << vec.size() << std::endl;
    std::cout << "Vector capacity: " << vec.capacity() << std::endl;

    // Delete the last element
    vec.pop_back();
    std::cout << "After pop_back, size: " << vec.size() << std::endl;

    return 0;
}

3. Boundary checking and safe access

Example

#include <iostream>
#include <vector>

int main() {
    std::vector<int> vec = {1, 2, 3};

    try {
        std::cout << vec.at(2) << std::endl;  // Normal output
        std::cout << vec.at(5) << std::endl;  // Out of range, throws an exception
    } catch (const std::out_of_range& e) {
        std::cout << "Exception: " << e.what() << std::endl;
    }

    return 0;
}

4. Preallocate capacity

Example

#include <iostream>
#include <vector>

int main() {
    std::vector<int> vec;
    vec.reserve(10);  // Reserve capacity to avoid frequent memory allocations

    for (int i = 0; i < 10; ++i) {
        vec.push_back(i);
        std::cout << "Capacity after push_back(" << i << "): " << vec.capacity() << std::endl;
    }

    return 0;
}

Comparison with other containers

Featuresstd::vectorstd::arraystd::list
SizeDynamically changeableFixed at compile timeDynamically changeable
Storage locationContiguous memoryContiguous memoryNon-contiguous memory
Access performanceFast random accessFast random accessRandom access is slow, suitable for sequential access
Insertion and deletion performanceEnd operations have high performance, other positions are slowerNot supportedInsertion and deletion at any position are relatively fast
Memory growth methodGrows exponentially when capacity is insufficientNoneNone

<vector>It is a very useful container in the C++ STL, providing dynamic array functionality that makes adding and removing elements more flexible and convenient. Through the above examples, beginners can quickly understand<vector>the basic usage and operations of it. As learning progresses, you will discover<vector>its powerful features and wide range of applications in practical programming.

other extensions