Creative Way to Initialize a Vector in C++

How can you initialize a vector in C++ with specific values based on input?

Four doubles are read from input as variables distance1 to distance4. Declare a vector of doubles named bikingDistance and initialize the elements at the even indices with the value 0 and the odd indices with the variables distance1 to distance4 in the order the input doubles are read. Ex: If the input is 5.06 20.58 6.5 19.94, how would you set up the vector?

Solution:

In this code, we first declare the four double variables `distance1` to `distance4` to read the input values. Then, we create a vector of doubles named `bikingDistance` and initialize its elements at even indices with 0 and at odd indices with the input values in the order they were read. Finally, we iterate over the vector and output each element separated by a space.

To achieve this, we can follow the code snippet below:


#include 
#include 

int main() {
    double distance1, distance2, distance3, distance4;
    std::cin >> distance1 >> distance2 >> distance3 >> distance4;
    
    // Initialize the vector with specific values based on input
    std::vector bikingDistance = {0, distance1, 0, distance2, 0, distance3, 0, distance4};
    
    // Output the vector elements
    for (const auto& distance : bikingDistance) {
        std::cout << distance << " ";
    }
    std::cout << std::endl;
    
    return 0;
}
    

If you run the program with the example input "5.06 20.58 6.5 19.94", the output will be "0 5.06 0 20.58 0 6.5 0 19.94" as expected.

← What is a pickup roller in a printer mechanism Which type of financial institution typically has membership requirements →