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

Why does using push_back on a vector declared with size result in a vector of zeros?

1个答案

1

In C++, initializing a vector with size specifies a certain number of elements, which are default-initialized. When you later use the push_back() method to add elements, these elements are appended after the already initialized elements, rather than replacing or clearing them.

For example, consider the following code:

cpp
#include <iostream> #include <vector> int main() { std::vector<int> vec(5); // Initialize a vector of size 5, with each element default-initialized to 0 vec.push_back(10); // Add element 10 to the end of the vector for (int i : vec) { std::cout << i << " "; // Output the vector elements } return 0; }

Running this code will output:

shell
0 0 0 0 0 10

As you can see, the initial vector consists of five default values of 0, and then 10 is added after these elements, resulting in six elements. This is how adding elements with push_back() works on a vector initialized with size.

If your goal is to create an empty vector and add elements only via push_back(), you should initialize the vector with the default constructor:

cpp
std::vector<int> vec; // Initialize an empty vector vec.push_back(10); // Add element 10 vec.push_back(20); // Add element 20 for (int i : vec) { std::cout << i << " "; // Output the vector elements }

This code will output:

shell
10 20

In this case, the vector contains only elements added via push_back().

2024年7月3日 23:21 回复

你的答案