Lecture 12. Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 1

Similar documents
Lecture 7. Log into Linux New documents posted to course webpage

Lecture 19. Wednesday, February 23 CS 215 Fundamentals of Programming II - Lecture 19 1

Templates and Vectors

Lectures 19, 20, 21. two valid iterators in [first, last) such that i precedes j, then *j is not less than *i.

STL: C++ Standard Library

Algorithms for Arrays Vectors Pointers CS 16: Solving Problems with Computers I Lecture #14

Vectors and Pointers CS 16: Solving Problems with Computers I Lecture #13

Lecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?

Bruce Merry. IOI Training Dec 2013

Purpose of Review. Review some basic C++ Familiarize us with Weiss s style Introduce specific constructs useful for implementing data structures

CSCI-1200 Data Structures Fall 2017 Lecture 9 Iterators & STL Lists

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

Chapter 5. The Standard Template Library.

Lecture 8. Xiaoguang Wang. February 13th, 2014 STAT 598W. (STAT 598W) Lecture 8 1 / 47

Computer Science II Lecture 2 Strings, Vectors and Recursion

CSCI-1200 Data Structures Fall 2010 Lecture 8 Iterators

Template based set of collection classes STL collection types (container types)

CS2255 HOMEWORK #1 Fall 2012

Midterm Practice Exam

CSCI-1200 Data Structures Fall 2014 Lecture 8 Iterators

STL components. STL: C++ Standard Library Standard Template Library (STL) Main Ideas. Components. Encapsulates complex data structures and algorithms

Outline. Review of Last Week II. Review of Last Week. Computer Memory. Review Variables and Memory. February 7, Data Types

Lecture 34. Wednesday, April 6 CS 215 Fundamentals of Programming II - Lecture 34 1

CS 215 Fundamentals of Programming II Spring 2011 Project 2

CS242 COMPUTER PROGRAMMING

SSE2034: System Software Experiment 3

Concurrent Data Structures in C++ CSInParallel Project

Topics. bool and string types input/output library functions comments memory allocation templates classes

CSCI-1200 Computer Science II Fall 2008 Lecture 15 Associative Containers (Maps), Part 2

Ali Malik Handout 12 CS106L Winter 2018 Jan 30th, C++ Reference

Type Aliases. Examples: using newtype = existingtype; // C++11 typedef existingtype newtype; // equivalent, still works

PIC10B/1 Winter 2014 Exam I Study Guide

Review Questions for Final Exam

Abstract Data Types (ADTs) 1. Legal Values. Client Code for Rational ADT. ADT Design. CS 247: Software Engineering Principles

CS197c: Programming in C++

Copyright 2003 Pearson Education, Inc. Slide 1

More Examples Using Functions and Command-Line Arguments in C++ CS 16: Solving Problems with Computers I Lecture #6

CS 247: Software Engineering Principles. ADT Design

PIC 10A. Final Review: Part I

CS31 Discussion 1E. Jie(Jay) Wang Week1 Sept. 30

Arrays - Vectors. Arrays: ordered sequence of values of the same type. Structures: named components of various types

G52CPP C++ Programming Lecture 18. Dr Jason Atkin

Homework 5. Yuji Shimojo CMSC 330. Instructor: Prof. Reginald Y. Haseltine

CSI33 Data Structures

Due Date: See Blackboard

CE221 Programming in C++ Part 1 Introduction

Arrays. Arizona State University 1

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

pointers & references

Function Templates. Consider the following function:

Fundamentals of Programming CS-110. Lecture 2

Computer Science II CSci 1200 Test 1 Overview and Practice

CSCI-1200 Data Structures Spring 2016 Lecture 7 Iterators, STL Lists & Order Notation

Working with Batches of Data

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

Practice Problems CS2620 Advanced Programming, Spring 2003

CSCI-1200 Data Structures Spring 2018 Lecture 14 Associative Containers (Maps), Part 1 (and Problem Solving Too)

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Computer Science II Lecture 1 Introduction and Background

Data Structures CSci 1200 Test 1 Questions

Programming Abstractions

Introduction to Programming using C++

CS11 Intro C++ Spring 2018 Lecture 2

Data Structures Lecture 3 Order Notation and Recursion

(6) The specification of a name with its type in a program. (7) Some memory that holds a value of a given type.

CS 117 Programming II, Spring 2018 Dr. Ghriga. Midterm Exam Estimated Time: 2 hours. March 21, DUE DATE: March 28, 2018 at 12:00 PM

Chapter 4 Computation

Exam 3 Chapters 7 & 9

Unit 1: Preliminaries Part 4: Introduction to the Standard Template Library

CS201 (Intro. to Computing) Sample Questions & Solutions for the FINAL Exam

Sonoma State University Computer Science Department CS 115 Fall 2010 Watts. Project 3 Part 1

Review: Expressions, Variables, Loops, and more.

Lectures 11,12. Online documentation & links

Spring 2003 Instructor: Dr. Shahadat Hossain. Administrative Matters Course Information Introduction to Programming Techniques

CS 103 Unit 12 Slides

CS183 Software Design. Textbooks. Grading Criteria. CS183-Su02-Lecture 1 20 May by Eric A. Durant, Ph.D. 1

(3) Some memory that holds a value of a given type. (8) The basic unit of addressing in most computers.

Recap. ANSI C Reserved Words C++ Multimedia Programming Lecture 2. Erwin M. Bakker Joachim Rijsdam

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

COEN244: Class & function templates

Scientific Computing

PIC 10A. Final Review

Chapter 4. Computation. Bjarne Stroustrup.

CISC 2200 Data Structure Fall, C++ Review:3/3. 1 From last lecture:

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

CS11 Introduction to C++ Fall Lecture 1

CSS 342 Data Structures, Algorithms, and Discrete Mathematics I. Lecture 2. Yusuf Pisan

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

I/O streams

CS 7A Final Exam Solutions - Spring Final Exam 5/24/16

Hashing. inserting and locating strings. MCS 360 Lecture 28 Introduction to Data Structures Jan Verschelde, 27 October 2010.

by Pearson Education, Inc. All Rights Reserved. 2

CS 103 Unit 11. Linked Lists. Mark Redekopp

Constants, References

CS11 Intro C++ Spring 2018 Lecture 3

G52CPP C++ Programming Lecture 18

! Search: find a given target item in an array, ! Linear Search: Very simple search method: ! Operators such as =, +, <, and others can be

CSCI-1200 Data Structures Spring 2015 Lecture 2 STL Strings & Vectors

C++ For Science and Engineering Lecture 12

Review Questions II KEY

Transcription:

Lecture 12 Log into Linux. Copy files on csserver in /home/hwang/cs215/lecture12/*.* Reminder: Practical Exam 1 is Wednesday 3pm-5pm in KC-267. Questions about Project 2 or Homework 6? Submission system is set up to accept submissions for both. Note: Please put your name (in a comment) in every file you submit! Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 1

Outline Note: this material is not directly in the textbook Introduction to templates and the STL STL vectors Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 2

Templates Often we want to use a container class to hold elements of different types in the same program. For example, a bag of integers to hold ages and a bag of strings to hold names. To use the implementation technique from last week, we would need to write two separate implementations with different class names E.g., integer_bag and string_bag. (Or use two different namespaces and always use qualified names. E.g. int_bag::bag and str_bag::bag.) Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 3

Templates The only difference between the two classes would be the typedef for value_type. Nothing else changes. However, it is tedious and error prone to have duplicate code. What is needed is a type parameter. This idea is like a regular data parameter except that it allows different types to be used. The built-in array is like this already. When we want an array, we just say what the element type is. Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 4

Templates The C++ mechanism for defining type parameters is called a template. Later in this course, we will write our own template functions and classes. Today we just want to start looking at the C++ Standard Template Library (STL). The STL defines 10 container classes that are categorized according to the ordering of the elements and the different kinds of operations that access the data. Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 5

Vectors The basic STL sequence container is the vector. A vector is like an array with added features. These are the most useful ones: it has constructors that initialize the vector, so that a vector is always in a valid state elements can be added dynamically to the end of a vector there is a member function that will return the number of elements in a vector. More details on vectors can be found on-line. Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 6

Vectors The vector<t> type is a template. It is defined in the <vector> library and is in namespace std. To use a template type, the actual type parameters are given in <>'s after the type name when declaring variables. Here are some examples using vector, which has one type parameter: vector<int> intvector; vector<double> realvector; vector<string> strvector; vector<rational> ratvector; // empty vectors Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 7

Constructors The vector default constructor creates an empty vector (i.e., 0 elements). Here are some other constructors: // 5 elements of T() = 0 vector<int> intvector2(5); // 31 elements of T() = 0/1 vector<rational> ratvector2(31); // 7 elements of 100 vector<int> intvector3(7, 100); // 7 elements of 4/3 // used Rational constructor directly vector<rational> ratvector3(7, Rational(4,3)); Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 8

Constructors There is no built-in initialization syntax like there is for arrays, but we can use an array to initialize a vector: int intarray[] = {9, 2, 7, 3, 12}; vector<int> intvector4(intarray, // addr of 1st element intarray + sizeof(intarray)/sizeof (int)); // addr of the element one past the end of the array The built-in sizeof function returns the number of bytes in a variable or a type, so sizeof(intarray)/sizeof(int) computes the number of elements in intarray. Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 9

Accessors Accessor operations of vector include: size returns the number of elements empty returns true if vector has no elements; false otherwise [ ] - indexing, like arrays, no bounds checking at also indexing, but checks bounds back returns a reference to the last element that can be used to access the value Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 10

Mutators and Operators Mutator operations of vector include: push_back add an element to the end pop_back remove an element from the end resize change the size of the vector; truncate if made smaller, fill if made larger clear make the vector empty back returns a reference to the last element that can be used to change it. Assignment (operator=) is defined for vectors. It causes the left operand to become a copy of the right operand. Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 11

Examples Examine file vector-examples.cpp. Since vectors are class objects, when they are passed as received-only parameters, they are passed using a const reference parameter. Note that the type returned by size( ) is size_t. As usual, g++ will give a warning if it is compared to an int. void PrintVector (const vector<int> & v) { for (size_t i = 0; i < v.size(); i++) cout << "Element " << i << ": " << v[i] << endl; } // end PrintVector Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 12

Examples // Demonstrate empty() and size() if (intvector.empty()) cout << "intvector is empty\n"; else cout << "intvector has " << intvector.size() << "elements\n"; // Demonstrate use of back() on either side of = cout << "The last element of intvector2 is " << intvector2.back() << endl; intvector2.back() = 5; cout << "The last element of intvector2 is now " << intvector2.back() << endl; // Demonstrate use of size() and [] cout << "The elements of intvector4 are:\n"; PrintVector (intvector4); Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 13

Examples // Double size of intvector4, fill with T()=0 intvector4.resize(2*intvector4.size()); // Resize intvector4 to 3 elements, truncate intvector4.resize(3); // Add some elements to end of intvector4 intvector4.push_back(5); intvector4.push_back(1); // Remove elements from end of intvector4 until empty while (!intvector4.empty()) { cout << "Removing end element " << intvector4.back() << endl; intvector4.pop_back(); } Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 14

Filling a Vector Unlike an array, the "slots" of a vector do not exist unless they are created during construction or by using push_back. But this means we can write a function that starts with an empty vector and fills it from values read in from an input stream (cin, an ifstream, or even an istringstream). E.g., ifstream instream ("inclass12.dat"); ReadVector(intVector, instream); Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 15

Filling a Vector // Fills a vector from an input stream void ReadVector (vector<int> & v, istream & in) { int value; v.clear(); // Want only elements from stream // Without clear() would be AppendToVector // read integers until end of file while (in >> value) v.push_back(value); // add to end of v } // end ReadVector Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 16

In-class Exercise Add a function SearchVector to the example program. This function receives a vector of integers and a target integer to search for. It returns the index (type size_t) of the target if found or the size of the vector if not found. Add code to the end of the main program to ask the user for a target value, call SearchVector, and display the index if the target was found or a message that the target was not found. Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 17

In-class Exercise Add a function JoinVectors to the example program. This function receives two vectors of integers and returns a (new) vector of integers that contains the elements of the first vector followed by the elements of the second vector. Add code to the end of the main program to join intvector and intvector3, and display the resulting vector. Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 18