Chapter 8. Strings and Vectors. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Similar documents
Chapter 8. Strings and Vectors. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Chapter 11. Friends, Overloaded Operators, and Arrays in Classes. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Copyright 2003 Pearson Education, Inc. Slide 1

Chapter 9. Pointers and Dynamic Arrays. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Chapter 10. Defining Classes. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Chapter 5. Functions for All Subtasks. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Chapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Computers and Scientific Thinking

Chapter 6. I/O Streams as an Introduction to Objects and Classes. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Chapter 2. C++ Basics. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

In this chapter, you will learn about: An Array Type for Strings. The Standard string Class. Vectors. Introduction Computer Science 1 CS 23021

Chapter 3. More Flow of Control. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Overview. Chapter 18 Vectors and Arrays. Reminder. vector. Bjarne Stroustrup

CS 11 C track: lecture 1

Recursion. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Review: Method Frames

. Written in factored form it is easy to see that the roots are 2, 2, i,

CMPT 125 Assignment 2 Solutions

CIS 121 Data Structures and Algorithms with Java Spring Stacks, Queues, and Heaps Monday, February 18 / Tuesday, February 19

Python Programming: An Introduction to Computer Science

10/23/18. File class in Java. Scanner reminder. Files. Opening a file for reading. Scanner reminder. File Input and Output

Chapter 1. Introduction to Computers and C++ Programming. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

! Given the following Structure: ! We can define a pointer to a structure. ! Now studentptr points to the s1 structure.

CIS 121 Data Structures and Algorithms with Java Spring Stacks and Queues Monday, February 12 / Tuesday, February 13

From last week. Lecture 5. Outline. Principles of programming languages

n Some thoughts on software development n The idea of a calculator n Using a grammar n Expression evaluation n Program organization n Analysis

CS : Programming for Non-Majors, Summer 2007 Programming Project #3: Two Little Calculations Due by 12:00pm (noon) Wednesday June

Classes and Objects. Again: Distance between points within the first quadrant. José Valente de Oliveira 4-1

n Maurice Wilkes, 1949 n Organize software to minimize errors. n Eliminate most of the errors we made anyway.

Ones Assignment Method for Solving Traveling Salesman Problem

n The C++ template facility provides the ability to define n A generic facility allows code to be written once then

Exercise 6 (Week 42) For the foreign students only.

Solution printed. Do not start the test until instructed to do so! CS 2604 Data Structures Midterm Spring, Instructions:

WORKED EXAMPLE 7.1. Producing a Mass Mailing. We want to automate the process of producing mass mailings. A typical letter might look as follows:

Abstract. Chapter 4 Computation. Overview 8/13/18. Bjarne Stroustrup Note:

Elementary Educational Computer

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

Computer Science Foundation Exam. August 12, Computer Science. Section 1A. No Calculators! KEY. Solutions and Grading Criteria.

CS200: Hash Tables. Prichard Ch CS200 - Hash Tables 1

Hash Tables. Presentation for use with the textbook Algorithm Design and Applications, by M. T. Goodrich and R. Tamassia, Wiley, 2015.

Analysis Metrics. Intro to Algorithm Analysis. Slides. 12. Alg Analysis. 12. Alg Analysis

Lecturers: Sanjam Garg and Prasad Raghavendra Feb 21, Midterm 1 Solutions

n n B. How many subsets of C are there of cardinality n. We are selecting elements for such a

Last Class. Announcements. Lecture Outline. Types. Structural Equivalence. Type Equivalence. Read: Scott, Chapters 7 and 8. T2 y; x = y; n Types

The Magma Database file formats

CSCI 123 INTRODUCTION TO PROGRAMMING CONCEPTS IN C++

Lecture Notes 6 Introduction to algorithm analysis CSS 501 Data Structures and Object-Oriented Programming

Threads and Concurrency in Java: Part 1

Python Programming: An Introduction to Computer Science

Threads and Concurrency in Java: Part 1

CIS 121. Introduction to Trees

6.854J / J Advanced Algorithms Fall 2008

Package RcppRoll. December 22, 2014

The Implementation of Data Structures in Version 5 of Icon* Ralph E. Gr is wo Id TR 85-8

Linked Lists 11/16/18. Preliminaries. Java References. Objects and references. Self references. Linking self-referential nodes

COP4020 Programming Languages. Subroutines and Parameter Passing Prof. Robert van Engelen

Oracle Server. What s New in this Release? Release Notes

Lecture 28: Data Link Layer

Pattern Recognition Systems Lab 1 Least Mean Squares

Message Integrity and Hash Functions. TELE3119: Week4

Recursion. Recursion. Mathematical induction: example. Recursion. The sum of the first n odd numbers is n 2 : Informal proof: Principle:

CSE 417: Algorithms and Computational Complexity

A New Morphological 3D Shape Decomposition: Grayscale Interframe Interpolation Method

top() Applications of Stacks

Morgan Kaufmann Publishers 26 February, COMPUTER ORGANIZATION AND DESIGN The Hardware/Software Interface. Chapter 5

Computational Geometry

The Open University, Walton Hall, Milton Keynes, MK7 6AA First published 2004

CS211 Fall 2003 Prelim 2 Solutions and Grading Guide

Graphs. Minimum Spanning Trees. Slides by Rose Hoberman (CMU)

Overview. Common tasks. Observation. Chapter 20 The STL (containers, iterators, and algorithms) 8/13/18. Bjarne Stroustrup

Lecture 7 7 Refraction and Snell s Law Reading Assignment: Read Kipnis Chapter 4 Refraction of Light, Section III, IV

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

27 Refraction, Dispersion, Internal Reflection

Algorithm. Counting Sort Analysis of Algorithms

Examples and Applications of Binary Search

On (K t e)-saturated Graphs

ECE4050 Data Structures and Algorithms. Lecture 6: Searching

University of Waterloo Department of Electrical and Computer Engineering ECE 250 Algorithms and Data Structures

5.3 Recursive definitions and structural induction

CSC165H1 Worksheet: Tutorial 8 Algorithm analysis (SOLUTIONS)

Sorting in Linear Time. Data Structures and Algorithms Andrei Bulatov

One advantage that SONAR has over any other music-sequencing product I ve worked

K-NET bus. When several turrets are connected to the K-Bus, the structure of the system is as showns

Getting Started. Getting Started - 1

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

3. b. Present a combinatorial argument that for all positive integers n : : 2 n

Data Structures and Algorithms Part 1.4

CSE 111 Bio: Program Design I Class 11: loops

APPLICATION NOTE PACE1750AE BUILT-IN FUNCTIONS

Graphic Standards for District Identification. September, 2012

Homework 1 Solutions MA 522 Fall 2017

CS 111: Program Design I Lecture 15: Objects, Pandas, Modules. Robert H. Sloan & Richard Warner University of Illinois at Chicago October 13, 2016

COSC 1P03. Ch 7 Recursion. Introduction to Data Structures 8.1

CS 111 Green: Program Design I Lecture 27: Speed (cont.); parting thoughts

Lecture 9: Exam I Review

Lecture 1: Introduction and Strassen s Algorithm

Major CSL Write your name and entry no on every sheet of the answer script. Time 2 Hrs Max Marks 70

EE University of Minnesota. Midterm Exam #1. Prof. Matthew O'Keefe TA: Eric Seppanen. Department of Electrical and Computer Engineering

9.1. Sequences and Series. Sequences. What you should learn. Why you should learn it. Definition of Sequence

3.1 Overview of MySQL Programs. These programs are discussed further in Chapter 4, Database Administration. Client programs that access the server:

why study sorting? Sorting is a classic subject in computer science. There are three reasons for studying sorting algorithms.

Transcription:

Chapter 8 Strigs ad Vectors Copyright 2015 Pearso Educatio, Ltd.. All rights reserved.

Overview 8.1 A Array Type for Strigs 8.2 The Stadard strig Class 8.3 Vectors Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-3

8.1 A Array Type for Strigs Copyright 2015 Pearso Educatio, Ltd.. All rights reserved.

A Array Type for Strigs C-strigs ca be used to represet strigs of characters C-strigs are stored as arrays of characters C-strigs use the ull character '\0' to ed a strig The Null character is a sigle character To declare a C-strig variable, declare a array of characters: char s[11]; Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-5

C-strig Details Declarig a C-strig as char s[10] creates space for oly ie characters The ull character termiator requires oe space A C-strig variable does ot eed a size variable The ull character immediately follows the last character of the strig Example: s[0] s[1] s[2] s[3] s[4] s[5] s[6] s[7] s[8] s[9] H i M o m! \0?? Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-6

C-strig Declaratio To declare a C-strig variable, use the sytax: char Array_ame[ Maximum_C_Strig_Size + 1]; + 1 reserves the additioal character eeded by '\0' Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-7

Iitializig a C-strig To iitialize a C-strig durig declaratio: char my_message[20] = "Hi there."; The ull character '\0' is added for you Aother alterative: char short_strig[ ] = "abc"; but ot this: char short_strig[ ] = {'a', 'b', 'c'}; Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-8

C-strig error This attempt to iitialize a C-strig does ot cause the \0 to be iserted i the array char short_strig[ ] = {'a', 'b', 'c'}; Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-9

Do't Chage '\0' Do ot to replace the ull character whe maipulatig idexed variables i a C-strig If the ull character is lost, the array caot act like a C-strig Example: it idex = 0; while (our_strig[idex]!= '\0') { our_strig[idex] = 'X'; idex++; } This code depeds o fidig the ull character! Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-10

Safer Processig of C-strigs The loop o the previous slide depeded o fidig the '\0' character It would be wiser to use this versio i case the '\0' character had bee removed it idex = 0; while (our_strig[idex]!= '\0' && idex < SIZE) { our_strig[idex] = 'X'; idex++; } Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-11

Assigmet With C-strigs This statemet is illegal: a_strig = "Hello"; This is a assigmet statemet, ot a iitializatio The assigmet operator does ot work with C-strigs Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-12

Assigmet of C-strigs A commo method to assig a value to a C-strig variable is to use strcpy, defied i the cstrig library Example: #iclude <cstrig> char a_strig[ 11]; strcpy (a_strig, "Hello"); Places "Hello" followed by the ull character i a_strig Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-13

A Problem With strcpy strcpy ca create problems if ot used carefully strcpy does ot check the declared legth of the first argumet It is possible for strcpy to write characters beyod the declared size of the array Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-14

A Solutio for strcpy May versios of C++ have a safer versio of strcpy amed strcpy strcpy uses a third argumet represetig the maximum umber of characters to copy Example: char aother_strig[10]; strcpy(aother_strig, a_strig_variable, 9); This code copies up to 9 characters ito aother_strig, leavig oe space for '\0' Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-15

== Alterative for C-strigs The == operator does ot work as expected with C-strigs The predefied fuctio strcmp is used to compare C- strig variables Example: #iclude <cstrig> if (strcmp(c_strig1, c_strig2)) cout << "Strigs are ot the same."; else cout << "Strig are the same."; Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-16

strcmp's logic strcmp compares the umeric codes of elemets i the C-strigs a character at a time If the two C-strigs are the same, strcmp returs 0 0 is iterpreted as false As soo as the characters do ot match strcmp returs a egative value if the umeric code i the first parameter is less strcmp returs a positive value if the umeric code i the secod parameter is less No-zero values are iterpreted as true Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-17

More C-strig Fuctios The cstrig library icludes other fuctios strle returs the umber of characters i a strig it x = strle( a_strig); strcat cocateates two C-strigs The secod argumet is added to the ed of the first The result is placed i the first argumet Example: char strig_var[20] = "The rai"; strcat(strig_var, "i Spai"); Now strig_var cotais "The raii Spai" Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-18

The strcat Fuctio strcat is a safer versio of strcat A third parameter specifies a limit for the umber of characters to cocateate Example: char strig_var[20] = "The rai"; strcat(strig_var, "i Spai", 11); Display 8.1 (1) Display 8.1 (2) Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-19

C-strigs as Argumets ad Parameters C-strig variables are arrays C-strig argumets ad parameters are used just like arrays If a fuctio chages the value of a C-strig parameter, it is best to iclude a parameter for the declared size of the C-strig If a fuctio does ot chage the value of a C-strig parameter, the ull character ca detect the ed of the strig ad o size argumet is eeded Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-20

C-strig Output C-strigs ca be output with the isertio operator Example: char ews[ ] = "C-strigs"; cout << ews << " Wow." << edl; Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-21

C-strig Iput The extractio operator >> ca fill a C-strig Whitespace eds readig of data Example: char a[80], b[80]; cout << "Eter iput: " << edl; ci >> a >> b; cout << a << b << "Ed of Output"; could produce: Eter iput: Do be do to you! DobeEd of Output Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-22

Readig a Etire Lie Predefied member fuctio getlie ca read a etire lie, icludig spaces getlie is a member of all iput streams getlie has two argumets The first is a C-strig variable to receive iput The secod is a iteger, usually the size of the first argumet specifyig the maximum umber of elemets i the first argumet getlie is allowed to fill Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-23

Usig getlie The followig code is used to read a etire lie icludig spaces ito a sigle C-strig variable char a[80]; cout << "Eter iput:\"; ci.getlie(a, 80); cout << a << Ed Of Output\"; ad could produce: Eter some iput: Do be do to you! Do be do to you!ed of Output Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-24

getlie wrap up getlie stops readig whe the umber of characters, less oe, specified i the secod argumet have bee placed i the C-strig oe character is reserved for the ull character getlie stops eve if the ed of the lie has ot bee reached Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-25

getlie ad Files C-strig iput ad output work the same way with file streams Replace ci with the ame of a iput-file stream i_stream >> c_strig; i_stream.getlie(c_strig, 80); Replace cout with the ame of a output-file stream out_stream << c_strig; Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-26

getlie sytax Sytax for usig getlie is ci.getlie(strig_var, Max_Characters + 1); ci ca be replaced by ay iput stream Max_Characters + 1 reserves oe elemet for the ull character Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-27

C-Strig to Numbers "1234" is a strig of characters 1234 is a umber Whe doig umeric iput, it is useful to read iput as a strig of characters, the covert the strig to a umber Readig moey may ivolve a dollar sig Readig percetages may ivolve a percet sig Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-28

C-strigs to Itegers To read a iteger as characters Read iput as characters ito a C-strig, removig uwated characters Use the predefied fuctio atoi to covert the C-strig to a it value Example: atoi("1234") returs the iteger 1234 atoi("#123") returs 0 because # is ot a digit Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-29

C-strig to log Larger itegers ca be coverted usig the predefied fuctio atol atol returs a value of type log Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-30

C-strig to double C-strigs ca be coverted to type double usig the predefied fuctio atof atof returs a value of type double Example: atof("9.99") returs 9.99 atof("$9.99") returs 0.0 because the $ is ot a digit Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-31

Library cstdlib The coversio fuctios atoi atol atof are foud i the library cstdlib To use the fuctios use the iclude directive #iclude <cstdlib> Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-32

Numeric Iput We ow kow how to covert C-strigs to umbers How do we read the iput? Fuctio read_ad_clea, i Display 8.2 Reads a lie of iput Discards all characters other tha the digits '0' through '9' Uses atoi to covert the "cleaed-up" C-strig to it Display 8.2 (1) Display 8.2 (2) Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-33

Cofirmig Iput Fuctio get_it, from Display 8.3 Uses read_ad_clea to read the user's iput Allows the user to reeter the iput util the user is satisfied with the umber computed from the iput strig Display 8.3 (1) Display 8.3 (2) Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-34

Sectio 8.1 Coclusio Ca you Describe the beefits of readig umeric data as characters before covertig the characters to a umber? Write code to do iput ad output with C-strigs? Use the atoi, atol, ad atof fuctios? Idetify the character that eds a C-strig? Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-35

8.2 The Stadard strig Class Copyright 2015 Pearso Educatio, Ltd.. All rights reserved.

The Stadard strig Class The strig class allows the programmer to treat strigs as a basic data type No eed to deal with the implemetatio as with C-strigs The strig class is defied i the strig library ad the ames are i the stadard amespace To use the strig class you eed these lies: #iclude <strig> usig amespace std; Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-37

Assigmet of Strigs Variables of type strig ca be assiged with the = operator Example: strig s1, s2, s3; s3 = s2; Quoted strigs are type cast to type strig Example: strig s1 = "Hello Mom!"; Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-38

Usig + With strigs Variables of type strig ca be cocateated with the + operator Example: strig s1, s2, s3; s3 = s1 + s2; If s3 is ot large eough to cotai s1 + s2, more space is allocated Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-39

strig Costructors The default strig costructor iitializes the strig to the empty strig Aother strig costructor takes a C-strig argumet Example: strig phrase; // empty strig strig ou("ats"); // a strig versio // of "ats" Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-40

Mixig strigs ad C-strigs It is atural to work with strigs i the followig maer strig phrase = "I love" + adjective + " " + ou + "!"; It is ot so easy for C++! It must either covert the ull-termiated C-strigs, such as "I love", to strigs, or it must use a overloaded + operator that works with strigs ad C-strigs Display 8.4 Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-41

I/O With Class strig The isertio operator << is used to output objects of type strig Example: strig s = "Hello Mom!"; cout << s; The extractio operator >> ca be used to iput data for objects of type strig Example: strig s1; ci >> s1; >> skips whitespace ad stops o ecouterig more whitespace Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-42

getlie ad Type strig A getlie fuctio exists to read etire lies ito a strig variable This versio of getlie is ot a member of the istream class, it is a o-member fuctio Sytax for usig this getlie is differet tha that used with ci: ci.getlie( ) Sytax for usig getlie with strig objects: getlie(istream_object, Strig_Object); Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-43

getlie Example This code demostrates the use of getlie with strig objects strig lie; cout "Eter a lie of iput:\"; getlie(ci, lie); cout << lie << "END OF OUTPUT\"; Output could be: Eter some iput: Do be do to you! Do be do to you!end OF OUTPUT Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-44

Character Iput With strigs The extractio operator caot be used to read a blak character To read oe character at a time remember to use ci.get ci.get reads values of type char, ot type strig The use of getlie, ad ci.get for strig iput are demostrated i Display 8.5 (1) Display 8.5 (2) Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-45

Aother Versio of getlie The versios of getlie we have see, stop readig at the ed of lie marker '\' getlie ca stop readig at a character specified i the argumet list This code stops readig whe a '?' is read strig lie; cout <<"Eter some iput: \"; getlie(ci, lie, '?'); Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-46

getlie Returs a Referece getlie returs a referece to its first argumet This code will read i a lie of text ito s1 ad a strig of o-whitespace characters ito s2: strig s1, s2; getlie(ci, s1) >> s2; returs ci >> s2; Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-47

getlie Declaratios These are the declaratios of the versios of getlie for strig objects we have see istream& getlie(istream& is, strig& str_var, char delimiter); istream& getlie(istream& is, strig& str_var); Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-48

Mixig ci >> ad getlie Recall ci >> skips whitespace to fid what it is to read the stops readig whe whitespace is foud ci >> leaves the '\' character i the iput stream Example: it ; strig lie; ci >> ; getlie(ci, lie); leaves the '\' which immediately eds getlie's readig lie is set equal to the empty strig Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-49

igore igore is a member of the istream class igore ca be used to read ad discard all the characters, icludig '\' that remai i a lie Igore takes two argumets First, the maximum umber of characters to discard Secod, the character that stops readig ad discardig Example: ci.igore(1000, '\'); reads up to 1000 characters or to '\' Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-50

Strig Processig The strig class allows the same operatios we used with C-strigs ad more Characters i a strig object ca be accessed as if they are i a array last_ame[i] provides access to a sigle character as i a array Idex values are ot checked for validity! Display 8.6 Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-51

Member Fuctio legth The strig class member fuctio legth returs the umber of characters i the strig object: Example: it = strig_var.legth( ); Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-52

Member Fuctio at at is a alterative to usig [ ]'s to access characters i a strig. at checks for valid idex values Example: strig str("mary"); Equivalet cout << str[6] << edl; cout << str.at(6) << edl; Equivalet str[2] = 'X'; str.at(2) = 'X'; Other strig class fuctios are foud i Display 8.7 Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-53

strig class to umbers C++11 has ew fuctios to covert a strig class object to a umber it i; double d; strig s; i = stoi("35"); // Coverts the strig "35" to a iteger 35 d = stod("2.5"); // Coverts the strig "2.5" to the double 2.5 C++11 has ew fuctios to covert a strig class object to a umber strig s = to_strig(1.2*2); // 2.4 stored i s Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 1-54

Compariso of strigs Compariso operators work with strig objects Objects are compared usig lexicographic order (Alphabetical orderig usig the order of symbols i the ASCII character set.) == returs true if two strig objects cotai the same characters i the same order Remember strcmp for C-strigs? <, >, <=, >= ca be used to compare strig objects Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-55

Program Example: Palidrome Testig A palidrome is a strig that reads the same from frot to back as it does from back to frot This program igores spaces ad puctuatio Upper ad lowercase versios of letters are cosidered the same letter Examples: Able was I 'ere I saw Elba. Madam, I'm Adam. A ma, a pla, a caal, Paama. Racecar Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-56

Palidrome Testig: remove_puct remove_puct removes puctuatio from a strig remove_puct compares each character i the strig to the characters i a strig cotaiig all the puctuatio characters ad the space character. If a match is ot foud, the character is added to the strig o_puct o_puct, the origial strig less ay puctuatio or spaces, is retured Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-57

Palidrome Testig: substr The substr member fuctio is used to locate a substrig withi a strig remove_puct uses substr to extract a sigle character at a time from the source strig. The character is stored i a_char. remove_puct the uses fuctio fid to see if the character i a_char is i the strig of puctuatio characters Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-58

Palidrome Testig: The Program The etire palidrome testig program is foud i Display 8.8 (1) Display 8.8 (2) Display 8.8 (3) Display 8.8 (4) Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-59

strig Objects to C-strigs Recall the automatic coversio from C-strig to strig: char a_c_strig[] = "C-strig"; strig_variable = a_c_strig; strigs are ot coverted to C-strigs Both of these statemets are illegal: a_c_strig = strig_variable; strcpy(a_c_strig, strig_variable); Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-60

Covertig strigs to C-strigs The strig class member fuctio c_str returs the C-strig versio of a strig object Example: strcpy(a_c_strig, strig_variable.c_str( ) ); This lie is still illegal a_c_strig = strig_variable.c_str( ) ; Recall that operator = does ot work with C- strigs Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-61

Sectio 8.2 Coclusio Ca you Show how a strig object ca be used like a C-strig? Write code to read a etire lie ito a strig object? Use the strig fuctio at to access idividual characters i a strig object? Write code to covert a strig to a C-strig? Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-62

8.3 Vectors Copyright 2015 Pearso Educatio, Ltd.. All rights reserved.

Vectors Vectors are like arrays that ca chage size as your program rus Vectors, like arrays, have a base type To declare a empty vector with base type it: vector<it> v; <it> idetifies vector as a template class You ca use ay base type i a template class: vector<strig> v; Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-64

Accessig vector Elemets Vectors elemets are idexed startig with 0 [ ]'s are used to read or chage the value of a item: v[i] = 42; cout << v[i]; [ ]'s caot be used to iitialize a vector elemet Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-65

Iitializig vector Elemets Elemets are added to a vector usig the member fuctio push_back push_back adds a elemet i the ext available positio Example: vector<double> sample; sample.push_back(0.0); sample.push_back(1.1); sample.push_back(2.2); Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-66

The size Of A vector The member fuctio size returs the umber of elemets i a vector Example: To prit each elemet of a vector give the previous vector iitializatio: for (it i= 0; i < sample.size( ); i++) cout << sample[i] << edl; Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-67

The Type usiged it The vector class member fuctio size returs a usiged it Usiged it's are oegative itegers Some compilers will give a warig if the previous for-loop is ot chaged to: for (usiged it i= 0; i < sample.size( ); i++) cout << sample[i] << edl; Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-68

Alterate vector Iitializatio A vector costructor exists that takes a iteger argumet ad iitializes that umber of elemets Example: vector<it> v(10); iitializes the first 10 elemets to 0 v.size( ) would retur 10 [ ]'s ca ow be used to assig elemets 0 through 9 push_back is used to assig elemets greater tha 9 Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-69

Vector Iitializatio With Classes The vector costructor with a iteger argumet Iitializes elemets of umber types to zero Iitializes elemets of class types usig the default costructor for the class Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-70

The vector Library To use the vector class Iclude the vector library #iclude <vector> Vector ames are placed i the stadard amespace so the usual usig directive is eeded: usig amespace std; Display 8.9 Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-71

vector Issues Attemptig to use [ ] to set a value beyod the size of a vector may ot geerate a error The program will probably misbehave The assigmet operator with vectors does a elemet by elemet copy of the right had vector For class types, the assigmet operator must make idepedet copies Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-72

vector Efficiecy A vector's capacity is the umber of elemets allocated i memory Accessible usig the capacity( ) member fuctio Size is the umber of elemets iitialized Whe a vector rus out of space, the capacity is automatically icreased A commo scheme is to double the size of a vector More efficiet tha allocatig smaller chuks of memory Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-73

Cotrollig vector Capacity Whe efficiecy is a issue Member fuctio reserve ca icrease the capacity of a vector Example: v.reserve(32); // at least 32 elemets v.reserve(v.size( ) + 10); // at least 10 more resize ca be used to shrik a vector Example: v.resize(24); //elemets beyod 24 are lost Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-74

Sectio 8.3 Coclusio Ca you Declare ad iitialize a vector of 10 doubles? Write code to icrease the size of a vector i at least two differet ways? Describe the differece betwee a vector's size ad its capacity? Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-75

Chapter 8 -- Ed Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-76

Display 8.1 (1/2) Back Next Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-77

Display 8.1 (2/2) Back Next Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-78

Display 8.2 (1/2) Back Next Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-79

Display 8.2 (2/2) Back Next Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-80

Display 8.3 (1/3) Back Next Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-81

Display 8.3 (2/3) Back Next Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-82

Display 8.3 (3/3) Back Next Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-83

Display 8.4 Back Next Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-84

Display 8.5 (1/2) Back Next Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-85

Display 8.5 (2/2) Back Next Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-86

Display 8.6 Back Next Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-87

Display 8.7 Back Next Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-88

Display 8.8 (1/4) Back Next Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-89

Display 8.8 (2/4) Back Next Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-90

Display 8.8 (3/4) Back Next Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-91

Display 8.8 (4/4) Back Next Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-92

Display 8.9 Back Next Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 8-93