Difference between vectors in C++
Difference between vectors in C++ |
Difference between vectors in C++
In C++, the vector
is a dynamic array that can grow in size. The three declarations you’ve provided are different ways to declare a vector, and here’s what each one means:
vector<int> result;
- This declares a vector named
result
that will store integers (int
). Initially, it is empty, and its size will grow dynamically as integers are added to it.
2. vector<int> result[10];
- This is actually an array of vectors. It declares an array named
result
with 10 elements, where each element is a vector that can store integers. Each vector in the array can grow independently in size.
3. vector<int> result(nums.size());
- This declares a vector named
result
that will store integers, and it is initialized to have a size equal tonums.size()
. Assumingnums
is another vector,result
will have the same number of elements asnums
from the start.
In summary:
- The first declaration is a single vector with a dynamic size.
- The second is an array of 10 vectors, each with a dynamic size.
- The third is a single vector whose initial size is set to the size of another vector,
nums
.
Here’s how you might visualize the differences:
// A single empty vector that can grow dynamically.
vector<int> result;
// An array of 10 vectors, each can grow dynamically.
vector<int> result[10];
// A single vector initialized to the size of 'nums'.
vector<int> result(nums.size());
Remember, the second declaration is not a vector but an array of vectors, which is a common point of confusion. The third declaration assumes that nums
is a previously defined vector and uses its size to initialize the result
vector. I hope this clarifies the differences for you! If you have any more questions or need further explanation, feel free to ask.
Comments
Post a Comment