- 1 year ago
Limit to size of array type, while there's not yet an instance
Comment
1 / 1
In C++, the size of an array type is known at compile-time, and it cannot be changed dynamically during runtime. When declaring an array, the size must be a constant expression.
If you need a collection with a dynamic size, you can consider using a container class like std::vector
from the C++ Standard Library. std::vector
provides dynamic resizing capabilities and can grow or shrink as needed. Unlike an array, you can add or remove elements from a std::vector
at runtime.
Here's an example of using std::vector
to create a collection with a dynamic size:
cpp#include <vector>
int main() {
std::vector<int> numbers; // Create an empty vector
// Add elements to the vector
numbers.push_back(10);
numbers.push_back(20);
numbers.push_back(30);
// Access elements in the vector
int firstElement = numbers[0];
int size = numbers.size();
// Iterate over the elements
for (int i = 0; i < numbers.size(); i++) {
// Do something with numbers[i]
}
return 0;
}
Using a container like std::vector
allows you to work with a collection of elements without the limitations of a fixed-size array.