Cis 223 Computer Science Ii Laboratory Four Vectors Vectors Thought Arrays Grow Shrink Len Q XXXXXXXXXX
CIS 223 Computer Science II
Laboratory Four
Vectors
Vectors can be thought of as arrays that can grow (and shrink)in length as needed while your program is running.
In C++ programs, the arrays that were created had a fixed lengthand the program could not change the length of the array once itstarted running. Vectors serve the same purpose as arrays, buttheir length can be changed when the program is running.
In order to use vectors in your C++ programs, you need toinclude:
#includeusing namespace std;.
Similar to arrays, vectors have a base type and will store acollection of values of its base type. We declare a variable,v, for a vector with base typeintas:
vector v;
The notationvectoris atemplate class, which means you can substitute anytype for theBase_Type.
Vector elements are indexed starting with 0. Example:
v[i] = 42;cout
Restrictions:
You can use the [ ] to change the value of the ithelement, but you cannot use this notation to initialize thatelement. Thus, you can only change an element that has already beengiven a value.
To add an element to a vector, you will use thepush_backfunction. You add elements to a vector in orderof positions, first at position 0, then position 1, then 2, and soforth. The functionpush_backwill add an element in thenext available position. Here is an example:
vector sample;sample.push_back(0.0);sample.push_back(1.1);sample.push_back(2.2);
These lines initialize the elements 0, 1, and 2 of the vectorsample to 0.0, 1.1, and 2.2.
The number of elements in a vector is called itssize. There is a member function, size( ), thatcan be used to determine the size of a vector.
To display the number of elements in vector sample (size of thevector) we will use:
cout
The size function returns anunsigned int,because thereturned value should always be positive.
There is a vector constructor which takes one integer and willinitialize the number of positions given as the argument. Forexample,
vector v(10);
initializes the first 10 elements of the vector v to 0. Thus, ifwe put thecout after thisstatement we will get a size of 10. Once this is done, then you canuse the [ ] to set other values for those elements.
for(int i = 0; i v[i] = 2*i;
Important note: It is worth noting that the number of vectorelements for which memory is allocated is called thecapacityof that vector. The capacity is not thesame thing as thesize,which is number ofelements with values. To determine the capacity of a vector, we usethecapacity( )function.
cout
will display the capacity of vector v.
Whenever a vector runs out of capacity and needs room for anadditional member, the capacity is automatically increased. Theincrease is usually done by doubling the existing capacity, butthis may not be efficient. There are two other functions that canbe used to change the capacity of a vector. The first function iscalledreserve(Limit).This function will explicitlyincrease the capacity byLimit. For example:
v.reserve(32);
will set the capacity to at least 32 elements.
The following call sets the capacity to at least 10 more thanthe number of elements currently in the vector.
v.reserve(v.size XXXXXXXXXX);
Note that thereserve( )function can increase thecapacity but may not be able to decrease the capacity. You canreduce the capacity using theresizefunction:
v.resize(24);
This resizes the vector to 24 elements. In the case that thereare more than 24 elements in the vector, the extra elements will bedistorted.
Following is a program in which we will use a vector to readsome values and to compute their average.
This program will ask for some values and display theiraverage
#include#includeusing namespace std;
int main( ){vector v(4);char ans = 'y';float sum = 0;int count = 0;
while(ans == 'y' || ans =='Y'){cout cin >> v[count];sum += v[count];
count++;
coutcin >> ans;}
if(count > 0){cout}
return 0;}
Exercise 1
Copy and paste or carefully type program aveVector_s.cpp andfilling the missing codes. Then compile it. Run the program for thefollowing cases:
1) 4 numbers: 2 2 22the average in this case is 22) 6 numbers: XXXXXXXXXXthe average is 2again3) 8 numbers: XXXXXXXXXXtheaverage in this case is 4.5
Did you get the correct answers?
Replace the i in the statement sum/count with one of the v.size() or v.capacity( ) that you think should produce the correctresults. Compile and run the program for the above three cases. Didyou get the correct results in all three cases?
Exercise 2
Complete popBack.cpp program popback_.cpp which demonstratesvector member functions.
This program demonstrates the vector member functions such aspush_back, pop_back, clear, size.
Exercise 3 Split function
Given the following split function header
vector split(string target, string delimiter);
Implement the function split so that it returns a vector of thestrings in target that are separated by the string delimiter. Forexample:
split("10,20,30", ",");