
PIC 10A: Introduction to Programming
UCLA Math Department
Summer 2009
Homework 3– Vector Library
Due Tuesday, July 14, 2009 4:00 PM Sharp
As a programmer you will spend lots of time working with vectors, thus it is important to feel
comfortable manipulating them. In this assignment we will write a small library for vector<int>.
A library is a collection of functions centered around a common theme. In our library, for example,
one function will calculate the partial sum for the elements in an vector. Another function will find
the position of an integer in a vector. For each function that you write the specification will tell
you the interface, that is, what parameters the function takes, what it returns, and what it must
do. It’s your job to decide how the function will do it (the implementation).
Two files will be provided, main.cpp and hwk3.cpp. The source file, hwk3.cpp, will contain your
implementation of the functions. The other source file, main.cpp, will test the implementation of
the functions in hwk3.cpp. You should add additional tests to this file. However, you will only turn
in hwk3.cpp. We will provide our own main.cpp that will thoroughly test your functions. You may
define additional functions in hwk3.cpp, but we will not directly call these functions.
Your program should build successfully. No function in hwk3.cpp should write to cout or read
from cin. If you would like to to print debugging messages use cerr instead.
You must implement these functions:
int tally(vector<int> v, int target);
Return the number of elements in the vector that are equal to target.
int mode(vector<int> v);
Return the value that occurs most frequently in a vector. If two or more values oc-
cur with the same frequency choose the one with the following property: the first
occurrence of chosen value in the vector has a smaller index than the first occur-
rence of the other values. (For example, if v.size() == 5 and v[0] == 1,v[1] == 2,
v[2] == 2,v[3] == 3, and v[4] == 1 then mode(v)==1.) If vis empty then mode
throws runtime_error.
int find_first(vector<int> v, int target);
Return the index of the first value in the vector that is equal to target. If this value
does not exist then throw runtime_error.
int partial_sum(vector<int>, int n);
Return the sum of the first nelements of vector. If nis greater than the size of the
vector or if nis less than zero throw runtime_error.
int position_of_min(vector<int> v);
Return the index of the smallest value in the vector. If this value occurs multiple times
return the smallest index. If vis empty throw runtime_error.