In C++, the std::vector class is a dynamic array that can be resized at runtime. It is part of the Standard Template Library (STL) and provides a more flexible alternative to static arrays.

Here is an example of 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 called numbers and add elements to it using the push_back function. We can access elements using indexing or iterators. The size function returns the number of elements in the vector. We can also resize the vector using the resize function, which allows us to change the size and optionally set a default value for new elements.

c++ verctor

原文地址: https://www.cveoy.top/t/topic/i5Zh 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录