0% found this document useful (0 votes)
3 views74 pages

Lecture18 Vectors

Uploaded by

Govind
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views74 pages

Lecture18 Vectors

Uploaded by

Govind
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 74

The Ohio State University 1

Vector Class
 What is a class?
 Data type

 What is a data type?


 A representation for a collection of values
 Operations over those values

 The data type int :


 Represents whole numbers (values)
 Defines operations +, -, *, /, %

The Ohio State University 2


C++ String Class (next week)
 The data type C++ string class:

 Represents text values


○ string lastName( “Wilcox”);
 Defines operations –
○ +, [], ==, !=, <, >, <=, >=
○ length(), substr(), replace(), insert()

 Apply the operation length() to the string value lastName

cout << lastName.length() << endl;

The Ohio State University 3


Recall Lists in C++
 A list is represented with an array
const int SIZE(10);
int list[SIZE];

 The array is a list representation from the


C programming language

 An alternative list representation is the


Vector class
 Overcomes limitations of arrays

The Ohio State University 4


Vector Class
 The data type Vector class:

 Represents a list of values

 Defines operations –
○ []
○ size(), push_back(), pop_back(),
resize(), clear()

The Ohio State University 5


Warning!
 Do not confuse a C++ vector with vector
in mathematics/geometry

 A geometric vector is a geometric object


which has both length and direction
 C++ vectors do not

The Ohio State University 6


Limitations of Arrays
 An array has fixed size
const MAX_SIZE(1000);
double A[MAX_SIZE];

 What if the user requires on average at most 10 double values out


of 1000 array locations?

 Used: 10 * 8 bytes = 80 bytes


 Wasted: 990 * 8 bytes = 7920 bytes
 Inefficient use of memory space

 What if the user sometimes requires more than 1000 array


locations?
 E.g., a user really needs 2000 locations

The Ohio State University 7


Vector Class
 A C++ vector class list can grow and shrink,
i.e. not fixed size

 Include the class definition

#include <vector>

 Declare a vector as a data type

vector<dataType> varName;

The Ohio State University 8


Vector Class
 A C++ vector class is an alternative to list
storage using C arrays

Compare …

 Array declaration
int list[]; // contains no values

 Vector declaration
vector<int> list; // contains no values

The Ohio State University 9


Vector Class
 Declare C++ vector class list with an initial size

 A vector with 10 integers


vector<int> list(10);
Initial
Allocation

Variable
Contains default values (later) Declaration

The Ohio State University 10


Vector Class
 Declare C++ vector class list with an initial size

 A vector with 10 integers


vector<int> list(10);

 A vector with 25 characters


vector<char> list(25);

 Compare to declaring with arrays


int list[10];
char list[25];

The Ohio State University 11


Vector Class
 Initial values are based on the data type in the
declaration

vector<int> list(5);

 This list contains { 0, 0, 0, 0, 0 }

 Declare with size and initial values

vector<int> list(5, 16);

 This list contains { 16, 16, 16, 16, 16 }


 Note the parenthesis

The Ohio State University 12


Vector Class
 Create vector with different values
vector <int> list = {35, 1, 22};
or
vector <int> list {35, 1, 22};
 This list contains { 35, 1, 22 }
 Note the curly braces

The Ohio State University 13


Vector Class: Storing List Values
 Use square bracket notation or .at( ) to store values in the
vector (same when using arrays)

 Allocation and initialization

vector<int> temps(3); 0 1 2
temps[0] = 79;
temps.at(1) = 90; 79 90 81
temps[2] = 81;

 The vector temps now contains { 79, 90, 81 };


 temps[0] refers to the first element, i.e. 79
 temps[1] refers to the second element, i.e. 90
 temps.at(2) refers to the third element, i.e. 81

The Ohio State University 14


Vector Class: Retrieve List Values
 Use square bracket notation or .at( ) to
access values in the vector (same when
using arrays)
vector<int> temps(3);
temps.at(0) = 79;
temps[1] = 90;
temps[2] = 81;

int x = temps[0]; // Retrieve 79


cout << temps.at(1); // Retrieve 90
double y = sqrt(double(temps[2])); // Retrieve 81

The Ohio State University 15


Vector Class: Update List Values
 Use square bracket notation or .at( ) to change
values in the vector (same when using arrays)
vector<int> temps(3);
temps[0] = 79;
temps[1] = 90;
temps.at(2) = 81;

temps[0] = 85; // Change 79 to 85


cin >> temps[1]; // Change 90 to user input
// or:
temps.at(0) = 85; // Change 79 to 85
cin >> temps.at(1); // Change 90 to user input

The Ohio State University 16


Vector Class: The size() function

 Use dot notation to apply class operations

 The size() function returns the number of


elements in the list

vector<int> temps(3);
cout << temps.size(); // Displays 3

 Note parenthesis "()" after size

The Ohio State University 17


Vector Class
 Just a variable declaration (no allocation)
creates a list with size 0
vector<int> temps;
cout << temps.size(); // Displays 0

 There are no positions yet in the list


temps[0]=10; is a run-time error & MAY display error
message
temps.at(0)=10; is a run-time error & WILL display
error message

The Ohio State University 18


Your Turn (together)
 Create a C++ vector with the values
{ 0, 1, 4, 9, 16, 25 }

 Use a loop to initialize the vector with


these values

 Observation:
{ 02, 12, 22, 32, 42, 52 }

The Ohio State University 19


0 1 2 3 4 5
Your Turn 0 1 4 9 16 25
. . .
#include <vector>

int main()
{
vector<int> v(6);

for (int i = 0; i < v.size(); i++) {


v[i] = i * i;
}

return 0;
}

The Ohio State University 20


Vector Class
 The data types int, double, char, and
bool are examples of basic data types,
sometimes called primitive data types

 The string data type is a class data type

 Create a vector to hold n string values


cout << "Enter how many strings: ";
cin >> n;
vector<string> str_list(n);

The Ohio State University 21


Your Turn (together):
Store Log Values

 Store log(k) into a list for k = 1, 2, …, n


 Ask the user for n

 First, try using an array


 Remember to use a constant for array size
 Next, try using a vector

The Ohio State University 22


logTable.cpp with array
...
const int SIZE(10);
double log_table[SIZE]; // array of SIZE elements
int n;

cout << "Enter number of integers: ";


cin >> n;
while (n > SIZE) {
cout << "Input error.";
cout << " Input must be less than or equal to "
<< SIZE << "." << endl;

cout << "Enter number of integers: ";


cin >> n;
}

The Ohio State University 23


logTable.cpp (cont.)
for (int i = 0; i < n; i++)
{
log_table[i] = log(double(i + 1));
}

for (int i = 0; i < n; i++)


{
cout << "log(" << i + 1 << ") = "
<< log_table[i] << endl;
}

return 0;
}

The Ohio State University 24


logTable2.cpp with vector
...
#include <vector>
...
int n(0);
cout << "Enter number of integers: ";
cin >> n;
// no need to validate n
vector<double> log_table(n); //use (n) tp give size

for (int i = 0; i < log_table.size(); i++)


{ log_table[i] = log(double(i + 1)); }

for (int i = 0; i < log_table.size(); i++)


{
cout << "log(" << i + 1 << ") = "
<< log_table[i] << endl;
}
...

The Ohio State University 25


logTableError.cpp
... Program produces no output.
#include <vector>
What is the error?
...
int n(0);
cout << "Enter number of integers: ";
cin >> n;

vector<double> log_table; Missing n so size( ) = 0

for (int i = 0; i < log_table.size(); i++)


{ log_table[i] = log(double(i + 1)); }

for (int i = 0; i < log_table.size(); i++)


{
cout << "log(" << i + 1 << ") = "
<< log_table[i] << endl;
}
...

The Ohio State University 26


logTableError2.cpp
... Program produces a runtime error.
#include <vector>
Why?
...
int n(0);
cout << "Enter number of integers: ";
cin >> n;

vector<double> log_table; Missing n so size( ) = 0


for (int i = 0; i < n; i++)
{ log_table[i] = log(double(i + 1)); } Element does not exist

for (int i = 0; i < n; i++)


{
cout << "log(" << i + 1 << ") = "
<< log_table[i] << endl;
}
...

The Ohio State University 27


Your Turn (together):
Display List In Reverse Order
 Ask the user for the number of list elements n

 Read the n elements from the user and store in


the list

 Display the list in reverse order

 First, use an array


 Remember to use a constant for array size
 Next, use a vector

The Ohio State University 28


reverse.cpp with array
...
const int ARRAY_SIZE(5);
int list[ARRAY_SIZE]; // an array of ARRAY_SIZE elements

cout << "Enter list of " << ARRAY_SIZE << " integers: ";
for (int i = 0; i < ARRAY_SIZE; i++)
{
cin >> list[i];
}

cout << "Reverse list: ";


for (int i = ARRAY_SIZE-1; i >= 0; i--)
{
cout << list[i] << " ";
}
cout << endl;
...

The Ohio State University 29


...
const int ARRAY_SIZE(5);
int list[ARRAY_SIZE]; // an array of ARRAY_SIZE elements

cout << "Enter list of " << ARRAY_SIZE << " integers: ";
for (int i = 0; i < ARRAY_SIZE; i++)
{
cin >> list[i];
}

cout << "Reverse list: ";


for (int i = ARRAY_SIZE-1; i >= 0; i--)
{
cout << list[i] << " ";
}
cout << endl;
...

> reverse.exe
Enter list of 5 integers: 1 2 3 4 5
Reverse list: 5 4 3 2 1

The Ohio State University 30


reverse2.cpp with vector
...
#include <vector>
...
int n(0);
cout << "Enter length of list: ";
cin >> n;

vector<int> list(n);

cout << "Enter list of " << list.size() << " integers: ";
for (int i = 0; i < list.size(); i++)
{ cin >> list[i]; }

cout << "Reverse list: ";


for (int i = list.size(); i > 0; i--)
{ cout << list[i - 1] << " "; }
cout << endl;

...

The Ohio State University 31


...
int n(0);
cout << "Enter length of list: ";
cin >> n;

vector<int> list(n);

cout << "Enter list of " << list.size() << " integers: ";
for (int i = 0; i < list.size(); i++)
{ cin >> list[i]; }

cout << "Reverse list: ";


for (int i = list.size(); i > 0; i--)
{ cout << list[i - 1] << " "; }
cout << endl;
...

> reverse2.exe
Enter length of list: 7
Enter list of 7 integers: 1 2 3 4 5 6 7
Reverse list: 7 6 5 4 3 2 1

The Ohio State University 32


The Ohio State University 33
Vector Class: 0
The push_back() function 78
 The push_back() function adds a 0 1
value at the end of the list
 Increases the size of the list by 1 78 81
 Returns nothing from function call 0 1 2

vector<int> grades; 78 81 65
0 1 2 3
grades.push_back(78);
grades.push_back(81); 78 81 65 90
grades.push_back(65);
0 1 2 3 4
grades.push_back(90);
grades.push_back(99); 78 81 65 90 99

The Ohio State University 34


Vector Class: The pop_back() function
 The pop_back() function removes a value at the end
of the list
 Decreases the size of the list by 1
 Does not return the value removed
0 1 2 3 4
vector<int> grades;

grades.push_back(78);
78 81 65 90 99
grades.push_back(81);
grades.push_back(65); 0 1 2 3
grades.push_back(90);
grades.push_back(99); 78 81 65 90
grades.pop_back(); // removes 99 0 1 2
grades.pop_back(); // removes 90
78 81 65
The Ohio State University 35
Vector Class: The erase() function
 The erase() function removes a value at a specific
position
 Decreases the size of the list by 1
 Does not return the value removed

vector<int> grades;
0 1 2 3 4
grades.push_back(78);
grades.push_back(81);
grades.push_back(65);
78 81 65 90 99
grades.push_back(90);
grades.push_back(99);
0 1 2 3
grades.erase(grades.begin()+2);
// removed 65 78 81 90 99

The Ohio State University 36


Vector Class: The resize() function
 The resize() function changes the size of the list
 Resets the size to the new size
 Does not return the value removed

vector<int> grades;
0 1 2
grades.push_back(78);
grades.push_back(81); 78 81 65
grades.push_back(65); 0 1 2 3 4
grades.resize(5, 27);
78 81 65 27 27
0 1 2 3
grades.resize(4); 78 81 65 27
Grades.resize(5); 0 1 2 3 4
78 81 65 27 0
The Ohio State University 37
Vector Class: The clear() function

 The clear() function removes all list values


 Sets the size of the list to 0
vector<int> grades;
0 1 2 3 4
grades.push_back(78);
grades.push_back(81); 78 81 65 90 99
grades.push_back(65);
grades.push_back(90);
grades.push_back(99);

cout << grades.size() << endl; // Displays 5

grades.clear();

cout << grades.size() << endl; // Displays 0

The Ohio State University 38


Your Turn (together):
Display List In Reverse Order
 Read a list of positive integers until the user
enters 0 and store in a list

 Use a vector
 Use the push_back() function

 Display the list in reverse order

The Ohio State University 39


reverse3.cpp
...
int val;
vector<int> list;

cout << "Enter list of positive integers (ending in 0): ";

cin >> val;


while (val > 0)
{
list.push_back(val); // add element val to back of list
cin >> val;
}

cout << "Reverse list: ";


for (int i = list.size(); i > 0; i--)
{ cout << list[i - 1] << " "; }
cout << endl;
...

The Ohio State University 40


...
int val;
vector<int> list;

cout << "Enter list of positive integers (ending in 0): ";

cin >> val;


while (val > 0)
{
list.push_back(val);
cin >> val;
}

cout << "Reverse list: ";


for (int i = list.size(); i > 0; i--)
{ cout << list[i - 1] << " "; }
cout << endl;
...

> reverse3.exe
Enter list of positive integers (ending in 0): 1 2 3 4 0
Reverse list: 4 3 2 1

The Ohio State University 41


reverseError.cpp What is the error?

...
int val; Does not use pushback()
vector<int> list;

cout << "Enter list of positive integers (ending in 0): ";


cin >> val;
int j = 0;
while (val > 0)
{
list.at(j) = val; // Memory for list[j] is not allocated.
cin >> val;
j++;
}

cout << "Reverse list: ";


for (int i = list.size(); i > 0; i--)
{ cout << list[i - 1] << " "; }
cout << endl;
...

The Ohio State University 42


reverseError.cpp
...
cout << "Enter list of positive integers (ending in 0): ";
cin >> val;
int j = 0;
while (val > 0)
{
list.at(j) = val; // ERROR. Memory for list[j] is not allocated.
cin >> val;
j++;
}

cout << "Reverse list: ";


for (int i = list.size(); i > 0; i--)
{ cout << list[i-1] << " "; }
cout << endl;
...

> reverseError.exe
Enter list of positive integers (ending in 0): 1 2 3 0
Segmentation fault

The Ohio State University 43


Your Turn (together):
Display List In Reverse Order
 Read a list of positive integers until the user
enters 0 and store in a list

 Use a vector
 Use the push_back() function

 Remove and display the list elements in


reverse order
 AND use the pop_back() function

The Ohio State University 44


reverse4.cpp
...
#include <vector>
...
int main()
{
int val;
vector<int> list;

cout << "Enter list of positive integers (ending in 0): ";

cin >> val;


while (val > 0)
{
list.push_back(val); // add element val to back of list
cin >> val;
}
...

The Ohio State University 45


reverse4.cpp (cont)
...
cout << "Reverse list: ";
while (list.size() > 0)
{
int n = list.size();
val = list[n - 1];
cout << val << " "; // display last element
list.pop_back(); // remove last element from list
}
cout << endl;
...

The Ohio State University 46


Summary: vector operations
vector<int> list, list2;

Some member functions of class vector:

 list[3] = 5; // store value


int x = list[3]; // read value
 list.size(); // number of elements
 list.push_back(5); // add element to back
 list.pop_back(); // remove last element
 list.clear(); // remove all elements
 list.erase(grades.begin()+2); // remove 1
 list.resize(newSize); // change vector size
 if (list == list2) … // returns true/false
The Ohio State University 47
The Ohio State University 48
Pass by Reference

 Class vector should always be passed by


reference
 Pass by reference is NOT the default

 Use const to indicate a vector which is not


going to be modified

The Ohio State University 49


Function findVectorMax()
#include <vector>
...
int findVectorMax(const vector<int> & v)
{
if (v.size() < 1) { return(0); }; // Logic error: return 0.

int vmax = v[0];


for (int i = 1; i < v.size(); i++)
{
if (v[i] > vmax)
{
vmax = v[i];
}
}
return(vmax);
}

The Ohio State University 50


vectorMax1().cpp
#include <vector>
...
int findVectorMax(const vector<int> & v); // function prototype
...
int main() {
int val(0), vmax(0);
vector<int> list;

cout << "Enter list of positive integers (ending in 0): ";


cin >> val;
while (val > 0) {
cin >> val;
list.push_back(val); // add element x to back of list
};

if (list.size() > 0)
{
vmax = findVectorMax(list);
cout << "Maximum integer = " << vmax << endl;
}
...

The Ohio State University 51


vectorMax1().cpp
...
cout << "Enter list of positive integers (ending in 0): ";
cin >> val;
while (val > 0) {
cin >> val;
list.push_back(val); // add element x to back of list
};

if (list.size() > 0)
{
vmax = findVectorMax(list);
cout << "Maximum integer = " << vmax << endl;
}
...

> vectorMax1.exe
Enter list of positive integers (ending in 0): 2 3 7 4 3 0
Maximum integer = 7

The Ohio State University 52


Standard Template Library (STL): swap()

 The swap function is defined in the


library algorithm

 Swaps the two values in parameters


 Uses pass by reference
 Works with arrays and vectors

 #include <algorithm>

The Ohio State University 53


Function moveVectorMax()
 Write a function moveVectorMax() that swaps
(“moves”) larger values to the first position

 The result is the maximum value is at the first position

 For example,

{ 5, 9, 10, 2 }
{ 5, 9, 10, 2 }
{ 9, 5, 10, 2 }
{ 10, 5, 9, 2 }
{ 10, 5, 9, 2 }

The Ohio State University 54


Function moveMax()using array
#include <algorithm>
...
void moveMax(int array[], const int size)
// Note: size is still const
{
for (int i = 1; i < size; i++)
{
if (array[0] < array[i])
{
swap(array[0], array[i]);
}
}
}

The Ohio State University 55


arrayMax4().cpp
// include & namespace statements
. . .
// function moveMax() prototype
void moveMax(int array[], const int size);

int main() // main function


{
const int SIZE_A(6);
int array_A[SIZE_A] = { 5, 3, 1, 7, 3, 5 };
const int SIZE_B(8);
int array_B[SIZE_B] = { 2, 6, 9, 0, 6, 4, 5, 1 };

moveMax(array_A, SIZE_A);
moveMax(array_B, SIZE_B);

cout << "Max of array A = " << array1[0] << endl;


cout << "Max of array B = " << array2[0] << endl;

return 0;
}

The Ohio State University 56


Function moveVectorMax()with Vector
#include <vector>
...
void moveVectorMax(vector<int> & v)
{
for (int i = 1; i < v.size(); i++)
{
if (v[0] < v[i])
{
swap(v[0], v[i]);
}
}
}

The Ohio State University 57


vectorMax2().cpp
#include <vector>
...
void moveVectorMax(vector<int> & v);
...
int val(0);
vector<int> list;

cout << "Enter list of positive integers (ending in 0): ";


cin >> val;
while (val > 0) {
cin >> val;
list.push_back(val); // add element x to back of list
};

if (list.size() > 0)
{
moveVectorMax(list);
cout << "Maximum integer = " << list[0] << endl;
}
...

The Ohio State University 58


Your Turn (together):
Reverse a List
 Write a function to reverse the elements in
a vector of integers in place by using the
swap function

The vector

{ 5, 9, 10, 2 }

change to

{ 2, 10, 9, 5 }

The Ohio State University 59


0 1 2 3
Reverse a List 78 81 65 90
0 1 2 3
 Will this work?
90 81 65 78
void reverse(vector<int> v)
{ 0 1 2 3
int n = v.size();
for (int i = 0; i < n/2; i++) 90 65 81 78
{
swap(v[i], v[n – 1 - i]); 0 1 2 3
} 90 65 81 78
}
// swap: [0] & [4 – 1 - 0]
// swap: [1] & [4 – 1 - 1]

The Ohio State University 60


Lets Define Function print_list
void print_list(const char label[],
const vector<int> v)
{
cout << label;
for (int i = 0; i < v.size(); i++) {
cout << v[i] << " ";
}
cout << endl;
}

The Ohio State University 61


reverseError2().cpp
// function prototypes
void reverse(vector<int> v);
void print_list(const char label[], const vector<int> v);

int main()
{
vector<int> list;

list.push_back(11);
list.push_back(12);
list.push_back(13);

print_list("List: ", list);


reverse(list);
print_list("Reverse list: ", list);

return 0;
}
The Ohio State University 62
reverseError2().cpp
// function prototypes
void reverse(vector<int> v);
void print_list(const char label[], const vector<int> v);

int main()
{
vector<int> list;

list.push_back(11);
list.push_back(12);
list.push_back(13);

print_list("List: ", list);


reverse(list);
print_list("Reverse list: ", list);

return 0;
}
What happened?
Why no reverse?
> reverseError2.exe
List: 11 12 13
Reverse List: 11 12 13

The Ohio State University 63


reverseError2().cpp
// reverse list
void reverse(vector<int> v)
{
int n = v.size(); Logic Error. A
for (int i = 0; i < n/2; i++) copy was passed.
{
swap(v[i], v[n – 1 - i]);
}
}

// print list
void print_list(const char label[], const vector<int> v)
{
cout << label;
for (int i = 0; i < v.size(); i++)
{ cout << v[i] << " "; } Bad
cout << endl; Performance
}
The Ohio State University 64
reverse5().cpp
// function prototypes
void reverse(vector<int> & v);
void print_list(const char label[], const vector<int> & v);

int main()
{
vector<int> list;

list.push_back(11);
list.push_back(12);
list.push_back(13);

print_list("List: ", list);


reverse(list);
print_list("Reverse list: ", list);

return 0;
}
The Ohio State University 65
reverse5().cpp
// reverse list
void reverse(vector<int> & v)
{
int n = v.size();
for (int i = 0; i < n/2; i++)
{
swap(v[i], v[n – 1 - i]);
}
}

// print list
void print_list(const char label[], const vector<int> & v)
{
cout << label;
for (int i = 0; i < v.size(); i++)
{ cout << v[i] << " "; }
cout << endl;
}
The Ohio State University 66
Standard Template Library (STL): sort()
 The sort function is defined in the library
algorithm

 Sorts the elements of a vector in increasing order

#include <algorithm>
#include <vector>

// sort from the beginning to the end


sort(list.begin(), list.end());

These are called “iterators”

The Ohio State University 67


sortInt().cpp
#include <algorithm>
#include <vector>
...
int main()
{
int val;
vector<int> list;

cout << "Enter list of positive integers (ending in 0): ";


cin >> val;
while (val > 0) {
cin >> val;
list.push_back(val); // add element val to back of list
}

sort(list.begin(), list.end());
for (int i = 0; i < list.size(); i++) {
cout << list[i] << " ";
}
cout << endl;
...

The Ohio State University 68


vectorMax3().cpp
#include <algorithm>
#include <vector>
...
int main()
{
int val;
vector<int> list;

cout << "Enter list of positive integers (ending in 0): ";


cin >> val;
while (val > 0) {
cin >> val;
list.push_back(val); // add element x to back of list
}

sort(list.begin(), list.end()); Prints largest value


if (list.size() > 0)
{
int k = list.size() - 1;
cout << "Maximum integer = " << list[k] << endl;
}
...
The Ohio State University 69
sortString().cpp
#include <algorithm>
#include <vector>
#include <string>
...
int main()
{ Vector of strings
string s;
vector<string> list;

cout << "Enter list of strings (ending with the string \".\"): ";
cin >> s;
while (s != ".") {
cin >> s;
list.push_back(s); // add element s to back of list
}

sort(list.begin(), list.end());
for (int i = 0; i < list.size(); i++) {
cout << list[i] << " ";
}
cout << endl;
...

The Ohio State University 70


So, Why Use Arrays at All?!
 Overhead
 Vectors use more space and (sometimes) take more time
than arrays

 When should arrays be used over vectors?


 When the array has fixed length
 When the dataset does not need to be contracted or
expanded
 When the array is 2 (or 3 or 4) dimensional
 When speed is an issue

 Note:
 C++ vectors are implemented using C arrays

The Ohio State University 71


Your Turn: Salary Analysis
A start-up company has paid you to write a C++
program to perform a salary analysis. Your program
should:
1. Prompt user & read in integer salaries until user
enters a value of zero (0). Store in a vector.
✓ In this step, do not keep running totals or highest.
2.Calculate & print total salaries paid.
✓ Use separate function to calculate total salaries
3.Then calculate & print average salary paid.
4.Then print all salaries from lowest to highest.
5.Print all numbers with 2 decimal places.

The Ohio State University 72


Salary Analysis
#include <iostream>
#include <vector>
#include <algorithm>
#include <iomanip>
using namespace std;

// function prototype:
double calculateTotalSalaries(const vector<int> &);

int main( ){
int numberOfSalaries(0), salary, i;
double totalSalaries;
vector<int> salaries;
cout << "Enter salaries; end with zero: ";
cin >> salary;
while (salary > 0) {
salaries.push_back(salary);
cin >> salary;
}
totalSalaries = calculateTotalSalaries(salaries);
cout << fixed << setprecision(2);
cout << "Total salaries paid = " << totalSalaries << endl;
CSE1222: Lecture 18 The Ohio State University 73
Salary Analysis (continued)
cout << "Average salary paid = "
<< totalSalaries / salaries.size() << endl;

sort(salaries.begin(), salaries.end());
cout << "All salaries (lowest to highest): ";
for(i=0; i<salaries.size(); i++)
cout << 1.0 * salaries[i] << " ";
cout << endl;

return 0;
}

double calculateTotalSalaries(const vector<int> & allSalaries) {


double total=0;
for(int i=0; i<allSalaries.size(); i++) total += allSalaries[i];
return total;
}

CSE1222: Lecture 18 The Ohio State University 74

You might also like