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

Similar documents
CSCI-1200 Data Structures Fall 2017 Lecture 2 STL Strings & Vectors

Computer Science II Lecture 2 Strings, Vectors and Recursion

Working with Batches of Data

CSCI-1200 Data Structures Fall 2012 Lecture 5 Pointers, Arrays, Pointer Arithmetic

CSCI-1200 Data Structures Spring 2014 Lecture 5 Pointers, Arrays, Pointer Arithmetic

CSCI-1200 Data Structures Fall 2013 Lecture 9 Iterators & Lists

CSCI-1200 Data Structures Spring 2018 Lecture 10 Vector Iterators & Linked Lists

Computer Science II Lecture 1 Introduction and Background

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

CSCI-1200 Data Structures Fall 2017 Lecture 10 Vector Iterators & Linked Lists

Working with Strings. Lecture 2. Hartmut Kaiser. hkaiser/spring_2015/csc1254.html

Introduction to C++ Introduction to C++ 1

CSCI-1200 Data Structures Fall 2018 Lecture 5 Pointers, Arrays, & Pointer Arithmetic

CSCI-1200 Data Structures Spring 2017 Lecture 5 Pointers, Arrays, Pointer Arithmetic

Computer Science II CSci 1200 Lecture 8 Iterators; Programming Examples

CSCI-1200 Data Structures Fall 2017 Lecture 12 Advanced Recursion

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

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

Biostatistics 615/815 Lecture 5: Divide and Conquer Algorithms Sorting Algorithms

Overloading Functions & Command Line Use in C++ CS 16: Solving Problems with Computers I Lecture #6

Announcements. CSCI 334: Principles of Programming Languages. Lecture 18: C/C++ Announcements. Announcements. Instructor: Dan Barowy

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

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

CE221 Programming in C++ Part 1 Introduction

Arrays. Week 4. Assylbek Jumagaliyev

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:

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

PHY4321 Summary Notes

Lab 15 Review of Arrays, Array of Objects and Vector Dr. John Abraham, Professor

CS 376b Computer Vision

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

CHAPTER 3 ARRAYS. Dr. Shady Yehia Elmashad

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

Computer Science II CSci 1200 Sections 6-10 Week 3, Monday Lecture January 28, 2002 Functions, Structs and Multiple Files

CSCI-1200 Data Structures Spring 2018 Lecture 5 Pointers, Arrays, & Pointer Arithmetic

Outline. Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples.

Arrays. Arizona State University 1

Data Structures CSci 1200 Test 2 Questions

CSCI-1200 Data Structures Fall 2017 Lecture 4 Classes II: Sort, Non-member Operators

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

Biostatistics 615/815 Lecture 5: More on STLs, and Divide and Conquer Algorithms

More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4

Lecture 5 Files and Streams

Data Structures CSci 1200 Test 1 Questions

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

Objectivities. Experiment 1. Lab6 Array I. Description of the Problem. Problem-Solving Tips

Programmazione. Prof. Marco Bertini

377 Student Guide to C++

Function Templates. Consider the following function:

CSCI-1200 Data Structures Spring 2018 Lecture 15 Associative Containers (Maps), Part 2

Chapter 15 - C++ As A "Better C"

CSCI-1200 Data Structures Spring 2017 Lecture 13 Advanced Recursion

CSCI-1200 Computer Science II Spring 2006 Lecture 10 Recursion Examples

Cours de C++ Introduction

Lecture on pointers, references, and arrays and vectors

Spring CS Homework 12 p. 1. CS Homework 12

CSCI-1200 Data Structures Fall 2009 Lecture 12 Advanced Recursion

CSCI-1200 Data Structures Spring 2016 Lecture 6 Pointers & Dynamic Memory

Chapter 7: Arrays Copyrig opy ht rig 2012 Pea e rson a Educa Educ ti a on, Inc I. nc

CSE 333. Lecture 10 - references, const, classes. Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington

CSCI-1200 Data Structures Fall 2017 Lecture 5 Pointers, Arrays, & Pointer Arithmetic

CSCI-1200 Data Structures Fall 2014 Lecture 12 Recursion

C++ Functions. Last Week. Areas for Discussion. Program Structure. Last Week Introduction to Functions Program Structure and Functions

PIC10B/1 Winter 2014 Exam I Study Guide

Data Structures Lecture 3 Order Notation and Recursion

(5-1) Object-Oriented Programming (OOP) and C++ Instructor - Andrew S. O Fallon CptS 122 (February 4, 2019) Washington State University

Introduction. Lecture 5 Files and Streams FILE * FILE *

Announcements. Lecture 05a Header Classes. Midterm Format. Midterm Questions. More Midterm Stuff 9/19/17. Memory Management Strategy #0 (Review)

CSCI-1200 Data Structures Fall 2016 Lecture 4 Classes II: Sort, Non-member Operators

Solving Problems Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

Lecture 04 FUNCTIONS AND ARRAYS

Lab Instructor : Jean Lai

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

Announcements. Lecture 04b Header Classes. Review (again) Comments on PA1 & PA2. Warning about Arrays. Arrays 9/15/17

Lecture 2, September 4

PROGRAMMING IN C++ CVIČENÍ

CSE 333 Final Exam June 6, 2017 Sample Solution

CSE 333 Lecture 9 - intro to C++

Functions and Recursion

7.1. Chapter 7: Arrays Hold Multiple Values. Array - Memory Layout. Array Terminology. Array Terminology

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

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

Lecture 15a Persistent Memory & Shared Pointers

Biostatistics 615/815 Lecture 6: Linear Sorting Algorithms and Elementary Data Structures

More on Func*ons Command Line Arguments CS 16: Solving Problems with Computers I Lecture #8

COMP 111 PROGRAMMING I MODULARITY USING FUNCTIONS

COMP322 - Introduction to C++ Lecture 01 - Introduction

My First Command-Line Program

Getting started with C++ (Part 2)

First C or C++ Lab Paycheck-V1.0 Using Microsoft Visual Studio

C++ Namespaces, Exceptions

Templates and Vectors

Exercise 1.1 Hello world

C++ Constructor Insanity

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

CS2255 HOMEWORK #1 Fall 2012

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

Intermediate Programming, Spring 2017*

CS61C Machine Structures. Lecture 3 Introduction to the C Programming Language. 1/23/2006 John Wawrzynek. www-inst.eecs.berkeley.

Transcription:

Announcements CSCI-1200 Data Structures Spring 2015 Lecture 2 STL Strings & Vectors HW 1 is available on-line through the website (on the Calendar ). Be sure to read through this information as you start implementation of HW1: Misc Programming Information (a link at the bottom of the left bar of the website). TA & instructor office hours are posted on website ( Weekly Schedule ). If you have not resolved issues with the C++ environment on your laptop, please do so immediately. If you cannot access the LMS site or the homework submission server, please email the instructor ASAP. Because many students were dealing with lengthy compiler/editor installation, registration confusion, etc., we will allow (for the first lab only!) students to get checked off for any remaining Lab 1 checkpoints at the beginning of next week s Lab 2 or in your grad TA s normal office hours. Today Finish Lecture 1 We left off around section 1.13. Value Parameters & Reference Parameters STL Strings L-values vs. R-values STL Vectors as smart arrays 2.1 Character Arrays and String Literals In the line below "Hello!" is a string literal and it is also an array of characters (with no associated variable name). cout << "Hello!" << endl; A char array can be initialized as: or as: char h[] = "Hello!"; char h[] = {'H', 'e', 'l', 'l', 'o', '!', '\0'; In either case, array h has 7 characters, the last one being the null character. The C and C++ languages have many functions for manipulating these C-style strings. We don t study them much anymore because the standard string library is much more logical and easier to use. One place we do use them is in file names and command-line arguments, which you will use in Homework 1. 2.2 Conversion Between Standard Strings and C-Style String Literals We regularly convert/cast between C-style & C++-style (STL) strings. For example: string s1( "Hello!" ); string s2( h ); where h is as defined above. You can obtain the C-style string from a standard string using the member function c_str, as in s1.c_str(). 2.3 Standard Library (STL) Vectors Example Motivating Problem: Read an unknown number of grades and compute some basic statistics such as the mean (average), standard deviation, median (middle value), and mode (most frequently occurring value). Accomplishing this requires the use of vectors. Why can t it be done (easily) with C-style arrays?

2.4 STL Vectors: C++ Arrays Standard library container class to hold sequences. A vector acts like a dynamically-sized, one-dimensional array. Capabilities: Holds objects of any type Starts empty unless otherwise specified Any number of objects may be added to the end there is no limit on size. It can be treated like an ordinary array using the subscripting operator. A vector knows how many elements it stores! (unlike C arrays) There is NO automatic checking of subscript bounds. Here s how we create an empty vector of integers: vector<int> scores; Vectors are an example of a templated container class. The angle brackets < > are used to specify the type of object (the template type ) that will be stored in the vector. push back is a vector function to append a value to the end of the vector, increasing its size by one. This is an O(1) operation (on average). There is NO corresponding push front operation for vectors. size is a function defined by the vector type (the vector class) that returns the number of items stored in the vector. After vectors are initialized and filled in, they may be treated just like arrays. In the line sum += scores[i]; scores[i] is an r-value, accessing the value stored at location i of the vector. We could also write statements like scores[4] = 100; to change a score. Here scores[4] is an l-value, providing the means of storing 100 at location 4 of the vector. It is the job of the programmer to ensure that any subscript value i that is used is legal - at least 0 and strictly less than scores.size(). 2.5 Initializing a Vector The Use of Constructors Here are several different ways to initialize a vector: This constructs an empty vector of integers. Values must be placed in the vector using push_back. vector<int> a; This constructs a vector of 100 doubles, each entry storing the value 3.14. New entries can be created using push_back, but these will create entries 100, 101, 102, etc. int n = 100; vector<double> b( 100, 3.14 ); This constructs a vector of 10,000 ints, but provides no initial values for these integers. Again, new entries can be created for the vector using push_back. These will create entries 10000, 10001, etc. vector<int> c( n*n ); This constructs a vector that is an exact copy of vector b. vector<double> d( b ); This is a compiler error because no constructor exists to create an int vector from a double vector. These are different types. vector<int> e( b ); 2

2.6 Exercises 1. After the above code constructing the three vectors, what will be output by the following statement? cout << a.size() << endl << b.size() << endl << c.size() << endl; 2. Write code to construct a vector containing 100 doubles, each having the value 55.5. 3. Write code to construct a vector containing 1000 doubles, containing the values 0, 1, 2, 3, 4, 5, etc. Write it two ways, one that uses push_back and one that does not use push_back. 2.7 Example: Using Vectors to Compute Standard Deviation Definition: If a 0, a 1, a 2,..., a n 1 is a sequence of n values, and µ is the average of these values, then the standard deviation is [ n 1 i=0 (a i µ) 2 ] 1 2 n 1 // Compute the average and standard deviation of an input set of grades. #include <fstream> #include <iomanip> #include <iostream> #include <vector> // to access the STL vector class #include <cmath> // to use standard math library and sqrt int main(int argc, char* argv[]) { if (argc!= 2) { std::cerr << "Usage: " << argv[0] << " grades-file\n"; std::ifstream grades_str(argv[1]); if (!grades_str.good()) { std::cerr << "Can not open the grades file " << argv[1] << "\n"; std::vector<int> scores; // Vector to hold the input scores; initially empty. int x; // Input variable // Read the scores, appending each to the end of the vector while (grades_str >> x) { scores.push_back(x); // Quit with an error message if too few scores. if (scores.size() == 0) { std::cout << "No scores entered. Please try again!" << std::endl; // program exits with error code = 1 // Compute and output the average value. int sum = 0; for (unsigned int i = 0; i < scores.size(); ++ i) { sum += scores[i]; double average = double(sum) / scores.size(); std::cout << "The average of " << scores.size() << " grades is " << std::setprecision(3) << average << std::endl; // Exercise: compute and output the standard deviation. double sum_sq_diff = 0.0; for (unsigned int i=0; i<scores.size(); ++i) { double diff = scores[i] - average; sum_sq_diff += diff*diff; double std_dev = sqrt(sum_sq_diff / (scores.size()-1)); std::cout << "The standard_deviation of " << scores.size() << " grades is " << std::setprecision(3) << std_dev << std::endl; 3

return 0; // everything ok 2.8 Standard Library Sort Function The standard library has a series of algorithms built to apply to container classes. The prototypes for these algorithms (actually the functions implementing these algorithms) are in header file algorithm. One of the most important of the algorithms is sort. It is accessed by providing the beginning and end of the container s interval to sort. As an example, the following code reads, sorts and outputs a vector of doubles: double x; std::vector<double> a; while ( std::cin >> x ) a.push_back(x); std::sort( a.begin(), a.end() ); for ( unsigned int i=0; i<a.size(); ++i ) std::cout << a[i] << '\n'; a.begin() is an iterator referencing the first location in the vector, while a.end() is an iterator referencing one past the last location in the vector. We will learn much more about iterators in the next few weeks. Every container has iterators: strings have begin() and end() iterators defined on them. The ordering of values by std::sort is least to greatest (technically, non-decreasing). We will see ways to change this. 2.9 Example: Computing the Median The median value of a sequence is less than half of the values in the sequence, and greater than half of the values in the sequence. If a 0, a 1, a 2,..., a n 1 is a sequence of n values AND if the sequence is sorted such that a 0 a 1 a 2 a n 1 then the median is a (n 1)/2 if n is odd // Compute the median value of an input set of grades. #include <algorithm> #include <cmath> #include <fstream> #include <iomanip> #include <iostream> #include <vector> a n/2 1 + a n/2 2 if n is even void read_scores(std::vector<int> & scores, std::ifstream & grade_str) { int x; // input variable while (grade_str >> x) { scores.push_back(x); void compute_avg_and_std_dev(const std::vector<int>& s, double & avg, double & std_dev) { // Compute and output the average value. int sum=0; for (unsigned int i = 0; i < s.size(); ++ i) { sum += s[i]; avg = double(sum) / s.size(); 4

// Compute the standard deviation double sum_sq = 0.0; for (unsigned int i=0; i < s.size(); ++i) { sum_sq += (s[i]-avg) * (s[i]-avg); std_dev = sqrt(sum_sq / (s.size()-1)); double compute_median(const std::vector<int> & scores) { // Create a copy of the vector std::vector<int> scores_to_sort(scores); // Sort the values in the vector. By default this is increasing order. std::sort(scores_to_sort.begin(), scores_to_sort.end()); // Now, compute and output the median. unsigned int n = scores_to_sort.size(); if (n%2 == 0) // even number of scores return double(scores_to_sort[n/2] + scores_to_sort[n/2-1]) / 2.0; else return double(scores_to_sort[ n/2 ]); // same as (n-1)/2 because n is odd int main(int argc, char* argv[]) { if (argc!= 2) { std::cerr << "Usage: " << argv[0] << " grades-file\n"; std::ifstream grades_str(argv[1]); if (!grades_str) { std::cerr << "Can not open the grades file " << argv[1] << "\n"; std::vector<int> scores; // Vector to hold the input scores; initially empty. read_scores(scores, grades_str); // Read the scores, as before // Quit with an error message if too few scores. if (scores.size() == 0) { std::cout << "No scores entered. Please try again!" << std::endl; // Compute the average, standard deviation and median double average, std_dev; compute_avg_and_std_dev(scores, average, std_dev); double median = compute_median(scores); // Output std::cout << "Among " << scores.size() << " grades: \n" << " average = " << std::setprecision(3) << average << '\n' << " std_dev = " << std_dev << '\n' << " median = " << median << std::endl; return 0; 2.10 Passing Vectors (and Strings) As Parameters The following outlines rules for passing vectors as parameters. The same rules apply to passing strings. If you are passing a vector as a parameter to a function and you want to make a (permanent) change to the vector, then you should pass it by reference. This is illustrated by the function read scores in the program median grade. This is very different from the behavior of arrays as parameters. 5

What if you don t want to make changes to the vector or don t want these changes to be permanent? The answer we ve learned so far is to pass by value. The problem is that the entire vector is copied when this happens! Depending on the size of the vector, this can be a considerable waste of memory. The solution is to pass by constant reference: pass it by reference, but make it a constant so that it can not be changed. This is illustrated by the functions compute avg and std dev and compute median in the program median grade. As a general rule, you should not pass a container object, such as a vector or a string, by value because of the cost of copying. 6