vectors

YoungJoon Suh·2023년 7월 8일

A vector is a kind of array whose length can dynamically grow and shrink.
Vectors are part of the C++ Standard Template Library (STL).
Like an array, a vector has a base type, and all its elements are of that type.
Different declaration syntax from arrays
vector salaries;
vector truth_table(10);
vector ages = {12, 9, 7, 2};

Index into a vector like an array: ages[2]
Use with a standard for loop:

for (int i = 0; i < ages.size(); i++)
{
cout << ages[i] << endl;
}

Or with a ranged for loop:
for (int age : ages)
{
cout << age << endl;
}

Append new values to the end of a vector
salaries.push_back(100000.0);
salaries.push_back(75000.0);
salaries.push_back(150000.0);
salaries.push_back(200000.0);

Vector assignment: v1 = v2;
Element-by-element assignment of values.
The size of v1 can change to match the size of v2.

Size of a vector: The current number of elements that the vector contains: v.size()
Capacity of a vector: The number of elements for which memory is currently allocated: v.capacity()

Change the size: v.resize(24)
Explicitly set the capacity: v.reserve(32)
Bump up the capacity by 10: v.reserve(v.capacity() + 10)

profile
저는 서영준 입니다.

0개의 댓글