Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

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 of strings l Arrays of doubles rThere are two issues with this style of programming l Suppose we want an array of student records, or hospital records l Suppose we do not know how big our array needs to be rThe first issue is overcome using structs and objects l We started looking at structs in the last lecture l We will look at Objects soon because they are very important and are like structs that have functions as well as data rThe second issue is overcome using the new STL Vector class l It comes loaded with useful methods l It can grow and shrink while a program executes

2 Lecture 1 -- 2Computer Science I - Martin Hardwick Vector rSyntax:Example: rThink of a vector as a way to create arrays that can grow bigger. l you can use a vector for any type of data l you can use it anywhere an array is required rTo access the components of a vector use the [] operator. rTo add an item to the end use push_back() rTo remove an item from the end use pop_back () rTo change an item use [] rTo test an item use == vector ;vector bank; vector numbers; numbers[10] = 99999; numbers.push_back (20); bank[i].put_name(Hardwick); if (bank[j].get_num () == 10000)

3 Lecture 1 -- 3Computer Science I - Martin Hardwick Study the following page rhttp://www.cprogramming.com/tutorial/stl/vector.htmlhttp://www.cprogramming.com/tutorial/stl/vector.html rUnderstand how to l Create a vector l Add items to a vector l Get items from a vector l Why vectors are good rVectors use STL l STL is the structured template language l An extension to C++ that gives great flexibility to the way classes and other structures are defined. l You can define STL classes for trees, lists, vectors and many other structures –More in CS 2 and DSA

4 Lecture 1 -- 4Computer Science I - Martin Hardwick Why Vectors are good rHave methods already programmed to let you add items, find items. l Size to find the size – makes parameter passing much easier l [] to get all the items – and will not go out of bounds l Some methods check the index to be sure it is valid rGrow as necessary so you do not have to reserve a large block of space. l Your simple application can become a big database l A matrix program does not have to start out using megabytes of space rMake your code easier to understand and trust because others know how to use Vector l Always best to use the same patterns as everyone else

5 Lecture 1 -- 5Computer Science I - Martin Hardwick Issues with Vector rThe 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 l Access to the heap is slightly slower than access to the stack (can matter for very long programs) l 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. l 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 rFor simple programs vector is the best choice rFor complex programs most are still using traditional arrays rHence we learn both in CS 1

6 Lecture 1 -- 6Computer Science I - Martin Hardwick Bank Simulation using Vector (1) #include using namespace std; // Create bank account data type struct acct { // bank account data int num; // account number string name; // owner of account floatbalance; // balance in account }; // Function Prototypes int find(vector bank, int goal); void insert(vector &bank, acct newacct); void remove(vector &bank, int acctnum); rThis program simulates a bank by processing transactions for bank accounts. rA vector is used to hold the list of bank accounts. rUnlike the previous version of this program (check Lecture 13) this version. l Does not need a parameter to give the size of the bank l Must pass the bank parameter by reference (&) so that the modified result is returned into the main program. l Uses #include to define the code for vectors.

7 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 accounts vector bank; // file with list of bank accounts ifstreamvault; // user request stringcommand; // account number to find intgoal; rThe main function creates the list of bank accounts and processes user commands to perform transactions. rNo limit on the number of bank accounts.

8 Lecture 1 -- 8Computer Science I - Martin Hardwick Bank Simulation using Vector (3) // subscript of account in bank intloc; // a bank account acctaccount; // read existing accounts from file vault.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 correctly cout << setiosflags(ios::fixed) << setprecision(2); rThe program assumes that a file named accounts.txt contains the data for existing accounts. rWe put the data into a variable and then add the variable to the bank. rThe push_back function adds the data to the bank vector.

9 Lecture 1 -- 9Computer Science I - Martin Hardwick Bank Simulation using vector (4) // get ready to process commands cout << "The bank is now open." ; cout << endl << endl; // loop to process user commands cout << 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); rOnly change on this page is the call to find () no longer includes numaccts.

10 Lecture 1 -- 10Computer Science I - Martin Hardwick Function Find using Vector (1) int find(vector 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 rParameters: vector of accounts, number of the goal account to find. rReturn: subscript of goal account if found, or –1 to indicate that it is not in the list. rSearch the vector from its beginning, element by element until: l find the account l reach the end of the list rThis is called a sequential search.

11 Lecture 1 -- 11Computer Science I - Martin Hardwick Function find using Vector (2) //search for the goal account in //the list of accounts for (k=0; k<bank.size(); k++) { if (bank[k].num == goal) { return k; } // didn't find goal account return -1; } rAgain the code is almost the same. rOnly difference is the condition of the while loop which now uses the size of the vector

12 Lecture 1 -- 12Computer Science I - Martin Hardwick Bank Simulation using vector (5) // display account data // or error message if (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; } rNo change at all rYou must change the other functions in the bank (list, insert and remove in your labs).


Download ppt "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."

Similar presentations


Ads by Google