12
Lecture 1 -- 1 Computer Science I - Martin Hardwick Making our programs more flexible So far we have largely programmed using Arrays of integers Arrays of strings Arrays of doubles There are two issues with this style of programming Suppose we want an array of student records, or hospital records Suppose we do not know how big our array needs to be The first issue is overcome using structs and objects We started looking at struct’s in the last lecture We will look at Objects soon because they are very important and are like struct’s that have functions as well as data The second issue is overcome using the new STL Vector class It comes loaded with useful methods It can grow and shrink while a program executes

Lecture 1 -- 1Computer Science I - Martin Hardwick Making our programs more flexible rSo far we have largely programmed using l Arrays of integers l Arrays

Embed Size (px)

Citation preview

Page 1: Lecture 1 -- 1Computer Science I - Martin Hardwick Making our programs more flexible rSo far we have largely programmed using l Arrays of integers l Arrays

Lecture 1 -- 1Computer Science I - Martin Hardwick

Making our programs more flexible

So far we have largely programmed using Arrays of integers Arrays of strings Arrays of doubles

There are two issues with this style of programming Suppose we want an array of student records, or hospital

records Suppose we do not know how big our array needs to be

The first issue is overcome using structs and objects We started looking at struct’s in the last lecture We will look at Objects soon because they are very important

and are like struct’s that have functions as well as data

The second issue is overcome using the new STL Vector class It comes loaded with useful methods It can grow and shrink while a program executes

Page 2: Lecture 1 -- 1Computer Science I - Martin Hardwick Making our programs more flexible rSo far we have largely programmed using l Arrays of integers l Arrays

Lecture 1 -- 2Computer Science I - Martin Hardwick

Vector

Syntax: Example:

Think of a vector as a way to create arrays that can grow bigger. you can use a vector for any type of data you can use it anywhere an array is required

To access the components of a vectoruse the [] operator.

To add an item to the end use push_back()

To remove an item from the enduse pop_back ()

To change an item use [] To test an item use ==

vector <type> <name>; vector <acct> bank;vector <int> numbers;

numbers[10] = 99999;numbers.push_back (20);bank[i].put_name(“Hardwick”);if (bank[j].get_num () == 10000)

Page 3: Lecture 1 -- 1Computer Science I - Martin Hardwick Making our programs more flexible rSo far we have largely programmed using l Arrays of integers l Arrays

Lecture 1 -- 3Computer Science I - Martin Hardwick

Study the following page

http://www.cprogramming.com/tutorial/stl/vector.html

Understand how to Create a vector Add items to a vector Get items from a vector Why vectors are good

Vectors use STL STL is the structured template language An extension to C++ that gives great flexibility to the way

classes and other structures are defined. You can define STL classes for trees, lists, vectors and

many other structures– More in CS 2 and DSA

Page 4: Lecture 1 -- 1Computer Science I - Martin Hardwick Making our programs more flexible rSo far we have largely programmed using l Arrays of integers l Arrays

Lecture 1 -- 4Computer Science I - Martin Hardwick

Why Vectors are good

Have methods already programmed to let you add items, find items. Size to find the size – makes parameter passing much

easier [] to get all the items – and will not go out of bounds Some methods check the index to be sure it is valid

Grow as necessary so you do not have to reserve a large block of space.

Your simple application can become a big database A matrix program does not have to start out using

megabytes of space

Make your code easier to understand and trust because others know how to use Vector

Always best to use the same patterns as everyone else

Page 5: Lecture 1 -- 1Computer Science I - Martin Hardwick Making our programs more flexible rSo far we have largely programmed using l Arrays of integers l Arrays

Lecture 1 -- 5Computer Science I - Martin Hardwick

Issues with Vector

The ability to grow requires the data be put in the heap instead of on the stack. More details on this later but for now you should know that

Access to the heap is slightly slower than access to the stack (can matter for very long programs)

Unused space on the heap has to be collected for reuse using a Garbage Collector. A typical system will avoid running the collector for as long as possible because it takes a long time to do its job and makes everything slow while it is running.

The importance of this issue is diminishing as programming systems become better at managing space – but it is a key reason why many programmers still use C++ instead of Java

For simple programs vector is the best choice

For complex programs most are still using traditional arrays

Hence we learn both in CS 1

Page 6: Lecture 1 -- 1Computer Science I - Martin Hardwick Making our programs more flexible rSo far we have largely programmed using l Arrays of integers l Arrays

Lecture 1 -- 6Computer Science I - Martin Hardwick

Bank Simulation using Vector (1)

#include <iostream>#include <iomanip>#include <string>#include <fstream>#include <vector>using namespace std;

// Create bank account data typestruct acct { // bank account data

int num; // account numberstring name; // owner of accountfloat balance; // balance in account

};

// Function Prototypesint find(vector <acct> bank, int goal);void insert(vector <acct> &bank,

acct newacct);void remove(vector <acct> &bank,

int acctnum);

This program simulates a bank by processing transactions for bank accounts.

A vector is used to hold the list of bank accounts.

Unlike the previous version of this program (check Lecture 13) this version.

Does not need a parameter to give the size of the bank

Must pass the bank parameter by reference (“&”) so that the modified result is returned into the main program.

Uses #include <vector> to define the code for vectors.

Page 7: Lecture 1 -- 1Computer Science I - Martin Hardwick Making our programs more flexible rSo far we have largely programmed using l Arrays of integers l Arrays

Lecture 1 -- 7Computer Science I - Martin Hardwick

Bank Simulation using Vector (2)

int main ()//PURPOSE: simulate a small bank//PRECONDITIONS: existing // accounts in file account.txt// in project folder//POSTCONDITIONS: finds,

inserts, // deletes, and lists accounts{

// list of bank accountsvector <acct> bank;

// file with list of bank accountsifstream vault;

// user requeststring command;

// account number to findint goal;

The main function creates the list of bank accounts and processes user commands to perform transactions.

No limit on the number of bank accounts.

Page 8: Lecture 1 -- 1Computer Science I - Martin Hardwick Making our programs more flexible rSo far we have largely programmed using l Arrays of integers l Arrays

Lecture 1 -- 8Computer Science I - Martin Hardwick

Bank Simulation using Vector (3)

// subscript of account in bank int loc;

// a bank account acct account;

// read existing accounts from filevault.open("accounts.txt");numaccts=0;vault >> account.num

>> account.name >> account.balance;

while (!vault.eof()) { bank.push_back (acct); vault >> account.num

>> account.name>> account.balance;

}

// display dollar values correctlycout << setiosflags(ios::fixed)

<< setprecision(2);

The program assumes that a file named accounts.txt contains the data for existing accounts.

We put the data into a variable and then add the variable to the bank.

The push_back function adds the data to the bank vector.

Page 9: Lecture 1 -- 1Computer Science I - Martin Hardwick Making our programs more flexible rSo far we have largely programmed using l Arrays of integers l Arrays

Lecture 1 -- 9Computer Science I - Martin Hardwick

Bank Simulation using vector (4)

// get ready to process commandscout << "The bank is now open." ;cout << endl << endl;

// loop to process user commandscout << endl << "----------" <<

endl;cout << "Enter command "

<< "(exit to stop): ";cin >> command;

while (command != "exit") {if (command == "find") {

// FIND COMMAND // get account to find cout << "Enter account num: "; cin >> goal; // search for account loc = find(bank, goal);

Only change on this page is the call to find () no longer includes numaccts.

Page 10: Lecture 1 -- 1Computer Science I - Martin Hardwick Making our programs more flexible rSo far we have largely programmed using l Arrays of integers l Arrays

Lecture 1 -- 10Computer Science I - Martin Hardwick

Function Find using Vector (1)

int find(vector <acct> bank, int goal)

//PURPOSE: search for a goal account // in the list of accounts

//PRECONDITIONS: 0 <= numaccts, // numaccts is number of accounts // in list of accounts (i.e., bank)

//POSTCONDITIONS: returns the // subscript of goal account or -1 if// the goal account is not found{

int k; // loop variable

Parameters: vector of accounts, number of the goal account to find.

Return: subscript of goal account if found, or –1 to indicate that it is not in the list.

Search the vector from its beginning, element by element until:

find the account reach the end of the list

This is called a sequential search.

Page 11: Lecture 1 -- 1Computer Science I - Martin Hardwick Making our programs more flexible rSo far we have largely programmed using l Arrays of integers l Arrays

Lecture 1 -- 11Computer Science I - Martin Hardwick

Function find using Vector (2)

//search for the goal account in //the list of accountsfor (k=0; k<bank.size(); k++) {

if (bank[k].num == goal) {

return k;}

}

// didn't find goal accountreturn -1;

}

Again the code is almost the same.

Only difference is the condition of the while loop which now uses the size of the vector

Page 12: Lecture 1 -- 1Computer Science I - Martin Hardwick Making our programs more flexible rSo far we have largely programmed using l Arrays of integers l Arrays

Lecture 1 -- 12Computer Science I - Martin Hardwick

Bank Simulation using vector (5)

// display account data // or error messageif (loc >= 0) {

cout << "Account: " << bank[loc].num << "\t" << "Owner: " << bank[loc].name << "\t" << "Balance: " <<

bank[loc].balance << endl;

}else {

cout << "Account " << goal <<" does not exist." << endl;

}}

No change at all

You must change the other functions in the bank (list, insert and remove in your labs).