Vector Initialization

We can initialize a vector in several ways:

1. Empty vector:

std::vector<int> numbers;  // Creates an empty vector

2. Vector with initial values:

std::vector<int> numbers = {1, 2, 3, 4};  // Vector with four numbers

3. Vector with several identical values:

std::vector<int> numbers(5, 0);  // Creates a vector with five zeros

Initialization examples with different data types:

std::vector<std::string> names = {"John", "Eva", "Tom"};  // Vector of texts
std::vector<double> prices = {29.90, 149.90, 99.90};     // Vector of decimal numbers
std::vector<bool> completed(3, false);                    // Three false values

Instructions

Create a vector of integers named grades and initialize it with initial values 1, 2, 1, 3.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

3/10

Vector Initialization | Start Coder