Notes week of Nov 21

vector-input.cpp

// CALL BY VALUE is the default way of passing parameters
// in C/C++: the parameter is a COPY of the original, so
// the function can't change the original.

// CALL BY REFERENCE is indicated by the (&) after the type
// of the parameter. It means the parameter is initialized
// as a reference to the original value, so it can change
// the original.

#include <iostream>
#include <vector>
using namespace std;

vector<float> read_numbers();
void read_numbers_into(vector<float>& numbers);

int main()
{
    //vector<float> numbers = read_numbers();
    vector<float> numbers;
    read_numbers_into(numbers);
    cout << "Got " << numbers.size() << " numbers.\n";
    for(unsigned int i = 0; i < numbers.size(); i++)
    {
        cout << numbers.at(i) << endl;
    }
    return 0;
}

vector<float> read_numbers()
{
    vector<float> numbers;
    cout << "Enter numbers, use -1 to end: ";
    float num;
    cin >> num;
    while(num != -1)
    {
        numbers.push_back(num);
        cin >> num;
    }
    return numbers;
}

// This is passing numbers BY REFERENCE so we can change it.
void read_numbers_into(vector<float>& numbers)
{
    cout << "Enter numbers, use -1 to end: ";
    float num;
    cin >> num;
    while(num != -1)
    {
        numbers.push_back(num);
        cin >> num;
    }
    cout << "DEBUG: numbers has " << numbers.size() << endl;
}