sizeof Replacement

Sizeof Replacement

Previously we had to use sizeof to get the number of element in an array without hardcoding a value.

Update this program to use std::vector and make use of the size function instead of using sizeof.

#include <iostream>

int main()
{
    float farray[5] = {1.5f, 3.f, 4.5f, 6.f, 7.5f};

    for (int i = 0; i < (sizeof(farray) / sizeof(farray[0])); i++)
    {
        std::cout << farray[i] << "\n";
    }
}

Answer

#include <iostream>
#include <vector>

int main()
{
    std::vector<float> farray = { 1.5f, 3.f, 4.5f, 6.f, 7.5f };

    for (int i = 0; i < farray.size(); i++)
    {
        std::cout << farray[i] << "\n";
    }
}
Questions