Notes week of Dec 8

vecinput.cpp

// vecinput.cpp
// Ask user to type in a sequence of numbers,
// and use -1 to indicate the end of the sequence.
#include <iostream>
#include <vector>
using namespace std;

vector<int> get_numbers_from_user();
int maximum(vector<int> vec);
int sum(vector<int> vec);
vector<int> filter_evens(vector<int> vec);

int main()
{
    vector<int> nums = get_numbers_from_user();
    cout << "I got " << nums.size() << " numbers." << endl;
    cout << "Largest is " << maximum(nums) << endl;
    vector<int> es = filter_evens(nums);
    cout << "There are " << es.size()
         << " evens:" << endl;
    for(int i = 0; i < es.size(); i++) {
        cout << es.at(i) << "  ";
    }
    cout << endl;
    return 0;
}

vector<int> get_numbers_from_user()
{
    vector<int> v;
    cout << "Enter numbers, ending with -1:" << endl;
    int x;
    cin >> x;
    while(x != -1) {
        v.push_back(x);
        cin >> x;
    }
    // simulate user entering numbers
    //v.push_back(13);
    //v.push_back(21);
    return v;
}

int maximum(vector<int> vec)
{
    if(vec.size() == 0) {
        cout << "Error: no maximum!" << endl;
        return 0; // ?
    }
    int biggest = vec.at(0); // will crash on empty list
    for(int i = 0; i < vec.size(); i++)
    {
        if(vec.at(i) > biggest)
        {
            biggest = vec.at(i);
        }
    }
    return biggest;
}

// If given the vector {3, 8, 6, 7, 2, 1, 9}
// it will return the vector {8, 6, 2}
vector<int> filter_evens(vector<int> vec)
{
    vector<int> evens;
    for(int i = 0; i < vec.size(); i++)
    {
        if(vec.at(i) % 2 == 0)
        {
            evens.push_back(vec.at(i));
        }
    }
    return evens;
}