乐闻世界logo
搜索文章和话题

How to set initial size of std::vector ?

1个答案

1

In C++, std::vector is a highly flexible container that can store a variable number of elements of the same type.

If you know the number of elements you will be processing, preallocating the initial capacity is a good practice, as it improves performance by avoiding multiple memory reallocations during runtime.

To set the initial capacity of std::vector, you can specify the size when creating the vector using its constructor. Here is a specific example:

cpp
#include <iostream> #include <vector> int main() { // Create a vector of int with initial capacity of 10 std::vector<int> vec(10); // Output the size of the vector std::cout << "The size of the vector is: " << vec.size() << std::endl; // Initialize the elements of the vector for (int i = 0; i < 10; ++i) { vec[i] = i * 10; } // Print the elements of the vector for (int val : vec) { std::cout << val << " "; } std::cout << std::endl; return 0; }

In this example, I created a std::vector<int> with an initial capacity of 10. This means that sufficient memory is allocated to store 10 int elements before any elements are actually added to the vector. Then, I initialize the values of these elements using a loop and print them.

Preallocating the capacity is a very useful optimization method, especially when you know the data size and want to avoid multiple memory reallocations when adding elements. This approach not only improves code performance but also makes memory management more efficient.

2024年6月29日 12:07 回复

你的答案