搜尋此網誌

2025年9月9日星期二

vector and range-based for loop

A vector in C++ is a dynamic array provided by the Standard Template Library (STL). Unlike regular arrays, vectors can resize automatically when elements are added or removed, making them incredibly flexible and widely used.

#include <iostream>

#include <vector>

using namespace std;


int main() {

    vector<int> numbers;           // Declare an empty vector of ints

    numbers.push_back(10);         // Add elements

    numbers.push_back(20);

    numbers.push_back(30);


    cout << "Size: " << numbers.size() << endl;  // Output: 3


    // Access elements

    cout << "First element: " << numbers[0] << endl;  // Output: 10


    // Update element

    numbers[1] = 25;


    // Traverse using range-based for loop

    for (int num : numbers) {

        cout << num << " ";

    }

    return 0;

}


numbers is a vector<int> — a dynamic array of integers.

for (int num : numbers) means:

👉 “For each element in the numbers vector, assign its value to num, and then execute the loop body.”

Inside the loop:

cout << num << " "; prints the current number followed by a space


Microsoft Copilot

沒有留言:

發佈留言