SoFunction
Updated on 2025-04-12

Specific use of std::vector in C++

In the C++ standard library, std::vector is a dynamic array class. Compared to static arrays, std::vector can automatically scale or shrink according to requirements, making it ideal for use in algorithm competitions. In Blue Bridge Cup matches, std::vector is often used to store dynamic data, handle array expansion problems, and can even replace two-dimensional arrays to simplify code.

1. The basic concept of std::vector

std::vector is a dynamic array container that can be dynamically resized as needed. Its underlying implementation is continuous blocks of memory that can support random access (i.e. access elements through indexes). Compared with ordinary arrays, it not only supports addition and deletion operations, but also automatically expands capacity, making it more flexible.

The internal mechanism of std::vectorThe dynamic expansion mechanism of std::vector is based onCapacityThe concept of  . vector maintains a preallocated block of memory internally to store elements. When the capacity is insufficient, the vector will automatically scale to 1.5 times or 2 times the original, reducing the overhead of frequently allocating memory.

2. Create std::vector

When creating std::vector, it can be initialized in different ways:

3. Dynamic scaling and capacity management

3.1 Dynamic expansion

When using push_back() to add elements to the vector, if the capacity is insufficient, the vector will automatically allocate more memory and re-copy existing elements, thereby expanding the capacity.

std::vector<int> vec;
for (int i = 0; i < 10; i++) {
    vec.push_back(i);
    std::cout << "Size: " << () << ", Capacity: " << () << std::endl;
}

3.2 Manual capacity management

If the vector size is known in advance, you can use the reserve() function to allocate memory, thereby avoiding the performance overhead of multiple expansions:

std::vector&lt;int&gt; vec;
(10); // Pre-allocated capacity is 10for (int i = 0; i &lt; 10; i++) {
    vec.push_back(i);
}

4. Common operations and methods

4.1 Adding and deleting elements

  • push_back(): Add an element at the end
  • pop_back(): Delete the end element
  • insert(): Insert element at the specified location
  • erase(): Delete elements at the specified location
  • clear(): Clear all elements
std::vector&lt;int&gt; vec = {1, 2, 3, 4, 5};
vec.push_back(6); // {1, 2, 3, 4, 5, 6}
vec.pop_back();   // {1, 2, 3, 4, 5}
(() + 2, 10); // {1, 2, 10, 3, 4, 5}
(() + 2); // {1, 2, 3, 4, 5}
(); // Clear all elements,size for 0

4.2 Access elements

  • Random access: Elements in vector can be accessed using indexes.
  • Border check: Use the at() method to provide out-of-bounds checking to prevent illegal access.
std::vector&lt;int&gt; vec = {1, 2, 3, 4, 5};
std::cout &lt;&lt; vec[0] &lt;&lt; std::endl;   // Output: 1std::cout &lt;&lt; (1) &lt;&lt; std::endl; // Output: 2,With boundary check

4.3 Iterator traversal

You can use an iterator to iterate through the vector. Use begin() and end() to get the head and tail position of the vector.

std::vector<int> vec = {1, 2, 3, 4, 5};
for (auto it = (); it != (); ++it) {
    std::cout << *it << " ";
}
std::cout << std::endl;

5. Application scenarios of std::vector in competitions

5.1 Dynamic data storage

In algorithm competitions, we often need to store unknown amounts of data. For example, when reading input data, std::vector can easily scale dynamically:

int n;
std::cin &gt;&gt; n;
std::vector&lt;int&gt; data;

for (int i = 0; i &lt; n; i++) {
    int x;
    std::cin &gt;&gt; x;
    data.push_back(x);
}

// Output all datafor (int x : data) {
    std::cout &lt;&lt; x &lt;&lt; " ";
}

5.2 Simulate stack structure

The push_back() and pop_back() operations provided by std::vector are similar to the data structure operations of the stack, so you can use vector to simulate the stack to solve problems such as bracket matching.

std::string s = "((()))";
std::vector&lt;char&gt; stack;

for (char c : s) {
    if (c == '(') {
        stack.push_back(c);
    } else if (!() &amp;&amp; () == '(') {
        stack.pop_back();
    }
}

if (()) {
    std::cout &lt;&lt; "Matching successfully!" &lt;&lt; std::endl;
} else {
    std::cout &lt;&lt; "Match failed!" &lt;&lt; std::endl;
}

5.3 Simulation of two-dimensional arrays

In the graph algorithm, it can be usedstd::vector<std::vector>to represent the adjacency matrix. Here is an example:

int n = 5; // Number of verticesstd::vector&lt;std::vector&lt;int&gt;&gt; graph(n, std::vector&lt;int&gt;(n, 0));

// Add edgesgraph[0][1] = 1;
graph[1][2] = 1;
graph[2][3] = 1;
graph[3][4] = 1;

// Output adjacency matrixfor (int i = 0; i &lt; n; i++) {
    for (int j = 0; j &lt; n; j++) {
        std::cout &lt;&lt; graph[i][j] &lt;&lt; " ";
    }
    std::cout &lt;&lt; std::endl;
}

6. Things to note

  • Performance optimization: Frequent dynamic scaling may lead to performance degradation. The capacity can be reserved() in advance if the size is known.
  • Border check:at() provides secure access, but if performance requirements are high, the [] operator can be used directly.
  • Two-dimensional vector: In the graph algorithm, try to choose the appropriate data structure to improve code efficiency.

This is the article about the specific use of std::vector in C++. For more related content on C++ std::vector, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!