C++ Programming. Arrays and Vectors. Chapter 6. Objectives. Chiou. This chapter introduces the important topic of data structures collections

Similar documents
by Pearson Education, Inc. All Rights Reserved. 2

C How to Program, 7/e by Pearson Education, Inc. All Rights Reserved.

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

C++ Programming Chapter 7 Pointers

Cpt S 122 Data Structures. Introduction to C++ Part II

Programming for Engineers Arrays

Chapter 7 Array. Array. C++, How to Program

Fundamentals of Programming Session 14

Chapter 8 Arrays and Strings. Objectives. Objectives (cont d.) Introduction. Arrays 12/23/2016. In this chapter, you will:

High Institute of Computer Science & Information Technology Term : 1 st. El-Shorouk Academy Acad. Year : 2013 / Year : 2 nd

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

Multiple-Subscripted Arrays

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book.

Lab Session # 5 Arrays. ALQUDS University Department of Computer Engineering

Deitel Series Page How To Program Series

Review of Important Topics in CS1600. Functions Arrays C-strings

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS

Chapter 12 Two-Dimensional Arrays

KOM3191 Object Oriented Programming Dr Muharrem Mercimek ARRAYS ~ VECTORS. KOM3191 Object-Oriented Computer Programming

Note 12/1/ Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance...

Lesson 06 Arrays. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Lecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays)

UEE1302 (1102) F10 Introduction to Computers and Programming (I)

Absolute C++ Walter Savitch

Lecture (07) Arrays. By: Dr. Ahmed ElShafee. Dr. Ahmed ElShafee, ACU : Fall 2015, Programming I

CSCE 206: Structured Programming in C++

CSCE 206: Structured Programming in C++

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program)

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) A few types

Fundamentals of Programming Session 23

A First Book of ANSI C Fourth Edition. Chapter 8 Arrays

ONE DIMENSIONAL ARRAYS

C++ PROGRAMMING SKILLS Part 4: Arrays

by Pearson Education, Inc. All Rights Reserved. 2

Abstract Data Type (ADT) & ARRAYS ALGORITHMS & DATA STRUCTURES I COMP 221

Pre Lab (Lab-1) Scrutinize Different Computer Components

Arrays. Comp Sci 1570 Introduction to C++ Array basics. arrays. Arrays as parameters to functions. Sorting arrays. Random stuff

Objectives. Chapter 8 Arrays and Strings. Objectives (cont d.) Introduction 12/14/2014. In this chapter, you will:

Problem Solving with C++

Character Functions & Manipulators Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10

CSC 307 DATA STRUCTURES AND ALGORITHM ANALYSIS IN C++ SPRING 2011

Instructor: Eng.Omar Al-Nahal

Introduction to C++ Introduction to C++ 1

Arrays. Lecture 9 COP 3014 Fall October 16, 2017

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7. CS 5301 Spring 2018

An array is a collection of data that holds fixed number of values of same type. It is also known as a set. An array is a data type.

More non-primitive types Lesson 06

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010

Objectives. In this chapter, you will:

Computer Programming C++ (wg) CCOs

CSCI 6610: Intermediate Programming / C Chapter 12 Strings

7.1. Chapter 7: Arrays Hold Multiple Values. Array - Memory Layout. A single variable can only hold one value. Declared using [] operator:

Chapter 7 : Arrays (pp )

Gabriel Hugh Elkaim Spring CMPE 013/L: C Programming. CMPE 013/L: C Programming

Arrays array array length fixed array fixed length array fixed size array Array elements and subscripting

Assignment 5: MyString COP3330 Fall 2017

Review of the C Programming Language for Principles of Operating Systems

Array Basics: Outline. Creating and Accessing Arrays. Creating and Accessing Arrays. Arrays (Savitch, Chapter 7)

11. Arrays. For example, an array containing 5 integer values of type int called foo could be represented as:

Chapter 9 Introduction to Arrays. Fundamentals of Java

Introduction to Programming using C++

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7.

V2 3/5/2012. Programming in C. Introduction to Arrays. 111 Ch 07 A 1. Introduction to Arrays

Functions. Introduction :

Functions, Arrays & Structs

The Foundation of C++: The C Subset An Overview of C p. 3 The Origins and History of C p. 4 C Is a Middle-Level Language p. 5 C Is a Structured

C: How to Program. Week /Apr/23

STIDistrict Query (Basic)

Learning Objectives. Introduction to Arrays. Arrays in Functions. Programming with Arrays. Multidimensional Arrays

Unit 14. Passing Arrays & C++ Strings

Outline. 7.1 Introduction. 7.2 Arrays. 7.2 Arrays

Introduction to C++ Systems Programming

A A B U n i v e r s i t y

Maltepe University Computer Engineering Department. BİL 133 Algorithms and Programming. Chapter 8: Arrays

C Arrays. Group of consecutive memory locations Same name and type. Array name + position number. Array elements are like normal variables

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

C++ Arrays. To declare an array in C++, the programmer specifies the type of the elements and the number of elements required by an array as follows

Here, type declares the base type of the array, which is the type of each element in the array size defines how many elements the array will hold

Definition Matching (10 Points)

Two Dimensional Array - An array with a multiple indexs.

7.1. Chapter 7: Arrays Hold Multiple Values. Array - Memory Layout. Array Terminology. Array Terminology 8/23/2014. Arrays Hold Multiple Values

Computer Programming: C++

Chapter 3: Arrays and More C Functionality

C Arrays Pearson Education, Inc. All rights reserved.

Chapter 6 SINGLE-DIMENSIONAL ARRAYS

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Arrays (Deitel chapter 7)

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Array Part dimensional arrays - 2-dimensional array operations - Arrays of Strings - N-dimensional arrays

CS201 Latest Solved MCQs

2 nd Week Lecture Notes

Functions, Arrays & Structs

Computer Science & Engineering 150A Problem Solving Using Computers

Introduction to C++ 2. A Simple C++ Program. A C++ program consists of: a set of data & function definitions, and the main function (or driver)

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows

String Objects: The string class library

C++ Arrays and Vectors

Transcription:

C++ Programming Chapter 6 Arrays and Vectors Yih-Peng Chiou Room 617, BL Building (02) 3366-3603 3603 ypchiou@cc.ee.ntu.edu.tw Photonic Modeling and Design Lab. Graduate Institute of Photonics and Optoelectronics & Department of Electrical Engineering National Taiwan University Objectives This chapter introduces the important topic of data structures collections of related data items. Arrays are data structures consisting of related data items of the same type. After discussing how arrays are declared, created and initialized, we present a series of practical examples that demonstrate several common array manipulations. 2

Contents 3 6.2 Arrays A consecutive group of memory locations that all have the same type. To refer to a particular location or element in the array specify the name of the array and the position number of the element an integer array called c. 12 elements. Position number, formally called a subscript or index (this number specifies the number of elements from the beginning of the array). 1 st element in every array has subscript 0 (zero), and is sometimes called the zeroth element. Highest subscript in array c is 11 (= 12-1) Avoid off-by-one error Specify an element explicitly, e.g., c[6], c[7] A subscript must be an integer or integer expression (using any integral type). 4

6.2 Arrays 5 6.3 Declaring Arrays Arrays occupy space in memory. Declaration form: type arrayname[ arraysize ]; The compiler reserves the appropriate amount of memory. Arrays can be declared to contain values of any nonreference data type. 6

6.4 Examples Using Array 6.4.1 6.4.1 Declaring an Array and Using a Loop to Initialize the Array s Elements Initializing an array s elements to zeros and printing the array 7 6.4 Examples Using Array 6.4.2 Initializing an Array in a Declaration with an Initializer List If there are fewer initializers than elements in the array, the remaining array elements are initialized to zero. (more => compilation error) If the array size is omitted from a declaration with an initializer list, the compiler determines the number of elements in the array by counting the number of elements in the initializer list. 8

6.4.3 Specifying an Array s Size with a Constant Variable and Setting Array Elements with Calculations The size of automatic and static arrays should be a constant. (dynamic => variable OK) 9 6.4.3 Specifying an Array s Size with a Constant Variable and Setting Array Elements with Calculations Line 10 uses the const qualifier to declare a so-called constant variablearraysize with the value 10. Constant variables must be initialized with a constant expression when they re declared and cannot be modified thereafter. Constant variables are also called named constants or read-only variables. 10

6.4.3 Specifying an Array s Size with a Constant Variable and Setting Array Elements with Calculations 11 12

6.4.4 Summing the Elements of an Array 13 6.4.5 Using Bar Charts to Display Array Data Graphically 14

6.4.5 Using Bar Charts to Display Array Data Graphically 15 6.4.6 Using the Elements of an Array as Counters 16

6.4.7 Using Arrays to Summarize Survey Results Uses arrays to summarize the results of data collected in a survey. Forty students were asked to rate the quality of the food in the student cafeteria on a scale of 1 to 10 (1 meaning awful and 10 meaning excellent). Place the 40 responses in an integer array and summarize the results of the poll. C++ has no array bounds checking to prevent the computer from referring to an element that does not exist. Thus, an executing program can walk off either end of an array without warning. You should ensure that all array references remain within the bounds of the array. 17 6.4.7 Using Arrays to Summarize Survey Results 18

6.4.7 Using Arrays to Summarize Survey Results 19 6.4.7 Using Arrays to Summarize Survey Results 20

6.4.8 Static Local Arrays and Automatic Local Arrays A program initializes static local arrays when their declarations are first encountered. If a static array is not initialized explicitly by you, each element of that array is initialized to zero by the compiler when the array is created. 21 6.4.8 Static Local Arrays and Automatic Local Arrays 22

6.4.8 Static Local Arrays and Automatic Local Arrays 23 6.4.8 Static Local Arrays and Automatic Local Arrays 24

6.4.8 Static Local Arrays and Automatic Local Arrays 25 6.5 Passing Arrays to Functions To pass an array argument to a function, specify the name of the array without any brackets. the array size is normally passed as well C++ passes arrays to functions by reference the called functions can modify the element in the callers original arrays. The value of the name of the array is the address in the computer s memory of the first element of the array. the called function knows precisely where the array is stored in memory Individual array elements are passed by value exactly as simple variable Such simple single pieces of data are called scalars or scalar quantities. 26

27 28

6.5 Passing Arrays to Functions 29 6.5 Passing Arrays to Functions 30

6.5 Passing Arrays to Functions (By structure or class) 31 6.6 Searching Arrays with Linear Search 32

Searching: determine whether an array of totally N elements contains a value that matches a certain key value. Linear search compares each element of an array with a search key No particular order: found in the 1st element as the last. On average, compare the search key with N/2 elements 33 6.7 Sorting Arrays with Insertion Sort Sorting data ( 排序 ) - placing the data into some particular order, e.g. ascending or descending an intriguing problem that has attracted some of the most intense research efforts in the field of computer science. Insertion sort a simple, but inefficient, sorting algorithm. Insert i-th elemenet into (i-1) sorted elements to make i sorted elements. i=1, no sorting i=2, i=3, 34

35 36

6.8 Multidimensional Arrays Arrays with two dimensions (i.e., subscripts) often represent tables of values consisting of information arranged in rows and columns. To identify a particular table element with two subscripts. By convention, the 1 st => row the 2 nd => column. Often called two-dimensional arrays or 2-D arrays. Arrays with two or more dimensions are known as multidimensional arrays. 37 6.8 Multidimensional Arrays Can be initialized in declaration, values grouped by row in braces If not enough initializers for a given row, remaining elements of that row are initialized to 0. 38

39 6.9 Case Study: Processing Grades in a Two-Dimensional Array 40

41 42

43 44

45 6.10 Introduction to C++ Standard Library Class Template vector vector: a more robust type of array featuring many additional capabilities C-style pointer-based arrays: potential for errors and are not flexible can easily walk off either end of an array, because C++ does not check Two arrays cannot be meaningfully compared with relational operators When an array is passed to a general-purpose function designed to handle arrays of any size, its size must be passed as an additional argument. One array cannot be assigned to another with the assignment operator(s). Class template vector allows you to create a more powerful and less error-prone alternative to arrays. Standard class template vector is defined in header <vector> and belongs to namespace std 46

47 48

49 50

51 6.10 Introduction to C++ Standard Library Class Template vector By default, all the elements of a vector object are set to 0. vectors can be defined to store any data type. vector member function size obtain the number of elements. U can use square brackets, [], to access the elements in a vector. vector objects can be compared with one another using the equality operators. You can create a new vector object that is initialized with a copy of an existing vector. You can use the assignment (=) operator with vector objects. As with C-style pointer-based arrays, C++ does not perform any bounds checking when vector elements are accessed with square brackets. Standard class template vector provides bounds checking in its member function at, which throws an exception (see Chapter 16, Exception Handling) if its argument is an invalid subscript. 52

6.11 Introduction to C++ Standard Library Class string 53 54

55 56

6.11 Introduction to C++ Standard Library Class string Line 16 reads the line of text from the user by using the library function getline (from the header file <string>). We can t simply write cin >> s4; to obtain a line of text. When cin is used with the stream extraction operator, it reads characters until the first white-space character is reached. Lines 27 33 show the results of comparing strings by using class string s overloaded equality and relational operators. These operators perform lexicographical comparisons on string objects they compare the numerical values of the characters (see Appendix B, ASCII Character Set) in each string. Class string provides member function empty, which returns true if the string is empty; otherwise, it returns false. 57 6.11 Introduction to C++ Standard Library Class string Line 41 demonstrates class x s overloaded assignment operator. Line 47 demonstrates class string s overloaded += operator for string concatenation. Line 52 demonstrates that a string literal can also be appended to a string object by using operator +=. Class string provides member function substr (lines 58 and 63) to return a portion of a string as a string object. The version with two arguments obtains the number of characters specified by the second argument starting at the position specified by the first argument. The single argument version obtains a substring starting from the specified index. Class string s overloaded [] operator can be used to create lvalues that enable new characters to replace existing characters in a string. No bounds checking is performed. 58

6.11 Introduction to C++ Standard Library Class string Classstring s overloaded[] operator can be used to obtain the character at a specified index. Classstring provides bounds checking in its member function at, which throws an exception if its argument is an invalid subscript. Erase a vector : http://www.cplusplus.com/reference/stl/vector/erase/ Two and multi-dimensional vectors 59