C++ Vector: Dynamic Arrays with STL
In C++, the 'std::vector' class is a dynamic array that can be resized at runtime. It's part of the Standard Template Library (STL) and offers a more flexible alternative to static arrays.
Here's an example demonstrating how to use 'std::vector' in C++:
#include <iostream>
#include <vector>
int main() {
// Create an empty vector
std::vector<int> numbers;
// Add elements to the vector
numbers.push_back(10);
numbers.push_back(20);
numbers.push_back(30);
// Access elements using indexing
std::cout << numbers[0] << std::endl; // Output: 10
// Access elements using iterator
for (std::vector<int>::iterator it = numbers.begin(); it != numbers.end(); ++it) {
std::cout << *it << " ";
}
std::cout << std::endl; // Output: 10 20 30
// Get the size of the vector
std::cout << "Size: " << numbers.size() << std::endl; // Output: 3
// Resize the vector
numbers.resize(5, 50); // Resize to 5 elements, with default value 50
// Print the vector after resizing
for (int i = 0; i < numbers.size(); i++) {
std::cout << numbers[i] << " ";
}
std::cout << std::endl; // Output: 10 20 30 50 50
return 0;
}
In this example, we create a vector named 'numbers' and add elements using the 'push_back' function. Elements can be accessed through indexing or iterators. The 'size' function returns the vector's element count. We can also resize the vector using the 'resize' function, which allows modifying the size and optionally setting a default value for new elements.
原文地址: https://www.cveoy.top/t/topic/mAVa 著作权归作者所有。请勿转载和采集!