Starting Out with C++, 3 rd Edition 1 7.14 Introduction to the STL vector The Standard Template Library (or STL) is a collection of data types and algorithms.

Slides:



Advertisements
Similar presentations
1 Arrays Chapter 9. 2 Outline  The array structure (Section 9.1)  Array declaration  Array initialization  Array subscripts  Sequential access to.
Advertisements

Beginning C++ Through Game Programming, Second Edition
Starting Out with C++, 3 rd Edition 1 Chapter 8 – Searching and Sorting Arrays.
Chapter 10.
1 CIS 205 Practice Test George Lamperti A word that has a predefined meaning in a C++ program and cannot be used as a variable name is known as.
Main Index Contents 11 Main Index Contents Container Types Container Types Sequence Containers Sequence Containers Associative Containers Associative Containers.
Starting Out with C++, 3 rd Edition 1 Chapter 9 – Pointers.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 11a. The Vector Class.
Chapter 7 Arrays C++ Programming, Namiq Sultan1 Namiq Sultan University of Duhok Department of Electrical and Computer Engineering Reference: Starting.
Lesson 7 Arrays CS 1 Lesson 7 -- John Cole1. Arrays Hold Multiple Values Array: variable that can store multiple values of the same type Values are stored.
Starting Out with C++, 3 rd Edition 1 Chapter 17 Linked Lists.
Functions Parameters & Variable Scope Chapter 6. 2 Overview  Using Function Arguments and Parameters  Differences between Value Parameters and Reference.
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
CS102 Introduction to Computer Programming Chapter 7 Arrays.
1 Chapter 3 Lists, Stacks, and Queues Abstract Data Types, Vectors Sections 3.1, 3.2, 3.3, 3.4 Abstract Data Types (ADT) Iterators Implementation of Vector.
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
11 COS220 Concepts of PLs AUBG, COS dept Lecture 36 OOP The STL Standard Template Library Reference: MS Developer Studio, Visual C++, Lafore, Chap 15 STL,
Introduction to STL and the vector container class CS342 Data Structures Based on Ford & Topp.
Main Index Contents 11 Main Index Contents Week 3 – The Vector Container.
Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays.
ARRAYS Lecture 2. 2 Arrays Hold Multiple values  Unlike regular variables, arrays can hold multiple values.
Value and Reference Parameters. CSCE 1062 Outline  Summary of value parameters  Summary of reference parameters  Argument/Parameter list correspondence.
CS102 Introduction to Computer Programming Chapter 9 Pointers.
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
Lecture: Arrays. 7.1 Arrays Hold Multiple Values.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
GE 211 Programming in C++ Array &Matrix Dr. Ahmed Telba.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
Lecture 7 : Intro. to STL (Standard Template Library)
Vectors One-Dimensional Containers. Problem A file contains a sequence of names and scores: Ann92 Bob84 Chris89... Using OCD, design and implement a program.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
Copyright © 2002 W. A. Tucker1 Chapter 9 Lecture Notes Bill Tucker Austin Community College COSC 1315.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 7 Arrays.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
Starting Out with C++, 3 rd Edition Array problem solving in C++ Dr Ahmed Telba.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
Lecture 14: Arrays Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
Chapter 7 Arrays Csc 125 Introduction to C++. Topics Arrays Hold Multiple Values Array Operations Arrays as function arguments Two-dimensional arrays.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 7: Arrays.
CSCI 161 Lecture 14 Martin van Bommel. New Structure Recall “average.cpp” program –Read in a list of numbers –Count them and sum them up –Calculate the.
Glenn Stevenson CSIS 113A MSJC CSIS 123A Lecture 3 Vectors.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 7- 1.
Lecture 8 – Array (Part 1) FTMK, UTeM – Sem /2014.
Copyright © 2012 Pearson Education, Inc. Chapter 7: Arrays.
Array. Array is a group of data of the same type. Array elements have a common name –The array as a whole is referenced through the common name Individual.
14-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN
ARRAYS (C) KHAERONI, M.SI. OVERVIEW Introduction to Arrays Arrays in Functions Programming with Arrays Multidimensional Arrays.
1 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long.
Chapter 7: Arrays. 7.1 Arrays Hold Multiple Values.
Chapter 8: Arrays. Arrays Hold Multiple Values Array: variable that can store multiple values of the same type Values are stored in adjacent memory locations.
Objectives You should be able to describe: One-Dimensional Arrays
Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays.
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
Chapter 7: Arrays.
Lecture 6 Arrays and Vectors
Chapter 7: Arrays.
Chapter 7 – Arrays.
Vectors Holds a set of elements, like an array
CSCE 210 Data Structures and Algorithms
Array An “average.cpp” program
New Structure Recall “average.cpp” program
Standard Version of Starting Out with C++, 4th Edition
CHAPTER 2 Arrays and Vectors.
CS150 Introduction to Computer Science 1
CHAPTER 2 Arrays and Vectors.
CS150 Introduction to Computer Science 1
8.3 Vectors Copyright © 2008 Pearson Addison-Wesley. All rights reserved. 1.
Presentation transcript:

Starting Out with C++, 3 rd Edition Introduction to the STL vector The Standard Template Library (or STL) is a collection of data types and algorithms that you may use in your programs. These data types and algorithms are programmer- defined. They are not part of the C++ language, but were created in addition to the built-in data types.

Starting Out with C++, 3 rd Edition Introduction to the STL vector The data types that are defined in the STL are commonly called containers, because they store and organize data. There are two types of containers in the STL: sequence containers and associative containers. The vector data type is a sequence container.

Starting Out with C++, 3 rd Edition Introduction to the STL vector A vector is like an array in the following ways: –A vector holds a sequence of values, or elements. –A vector stores its elements in contiguous memory locations. –You can use the array subscript operator [] to read the individual elements in the vector

Starting Out with C++, 3 rd Edition Introduction to the STL vector However, a vector offers several advantages over arrays. Here are just a few: –You do not have to declare the number of elements that the vector will have. –If you add a value to a vector that is already full, the vector will automatically increase its size to accommodate the new value. –vector s can report the number of elements they contain.

Starting Out with C++, 3 rd Edition 5 Declaring a vector To use vectors in your program, you must first #include the vector header file with the following statement: #include Note: There is no.h at the end of the file name.

Starting Out with C++, 3 rd Edition 6 Declaring a vector The next step is to include the following statement after your #include statements: using namespace std; The STL uses namespaces to organize the names of its data types and algorithms.

Starting Out with C++, 3 rd Edition 7 Declaring a vector Now you are ready to declare an actual vector object. Here is an example: vector numbers; The statement above declares numbers as a vector of int s.

Starting Out with C++, 3 rd Edition 8 Declaring a vector You can declare a starting size, if you prefer. Here is an example: vector numbers(10); The statement above declares numbers as a vector of 10 int s.

Starting Out with C++, 3 rd Edition 9 Other examples of vector Declarations Declaration FormatDescription vector amounts; Declares amounts as an empty vector of float s. vector scores(15); Declares scores as a vector of 15 int s. vector letters(25, 'A'); Declares letters as a vector of 25 characters. Each element is initialized with 'A'. vector values2(values1); Declares values2 as a vector of double s. All the elements of values1, which also a vector of doubles, are copied to value2.

Starting Out with C++, 3 rd Edition 10 Storing and Retrieving Values in a vector To store a value in an element that already exists in a vector, you may use the array subscript operator [].

Starting Out with C++, 3 rd Edition 11 Program 7-23 // This program stores, in two vectors, the hours worked by 5 // employees, and their hourly pay rates. #include using namespace std; #include // Needed to declare vectors using namespace std; int main() { vector hours(5); // Declare a vector of 5 integers vector payRate(5); // Declare a vector of 5 floats cout > hours[index]; cout > payRate[index]; }

Starting Out with C++, 3 rd Edition 12 Program 7-23 (continued) cout << "Here is the gross pay for each employee:\n"; cout.precision(2); cout.setf(ios::fixed | ios::showpoint); for (index = 0; index < 5; index++) { float grossPay = hours[index] * payRate[index]; cout << "Employee #" << (index + 1); cout << ": $" << grossPay << endl; } return 0; }

Starting Out with C++, 3 rd Edition 13 Program 7-23 (continued) Program Output with Example Input Shown in Bold Enter the hours worked by 5 employees and their hourly rates. Hours worked by employee #1: 10 [Enter] Hourly pay rate for employee #1: 9.75 [Enter] Hours worked by employee #2: 15 [Enter] Hourly pay rate for employee #2: 8.62 [Enter] Hours worked by employee #3: 20 [Enter] Hourly pay rate for employee #3: [Enter] Hours worked by employee #4: 40 [Enter] Hourly pay rate for employee #4: [Enter] Hours worked by employee #5: 40 [Enter] Hourly pay rate for employee #5: [Enter] Here is the gross pay for each employee: Employee #1: $97.50 Employee #2: $ Employee #3: $ Employee #4: $ Employee #5: $626.00

Starting Out with C++, 3 rd Edition 14 Using the push_back Member Function You cannot use the [] operator to access a vector element that does not exist. To store a value in a vector that does not have a starting size, or is already full, use the push_back member function. Here is an example: numbers.push_back(25);

Starting Out with C++, 3 rd Edition 15 Program 7-24 // This program stores, in two vectors, the hours worked by a specified // number of employees, and their hourly pay rates. #include using namespace std; #include // Needed to declare vectors using namespace std; int main() { vector hours; // hours is an empty vector vector payRate; // payRate is an empty vector int numEmployees; // The number of employees cout > numEmployees; cout << "Enter the hours worked by " << numEmployees; cout << " employees and their hourly rates.\n";

Starting Out with C++, 3 rd Edition 16 Program 7-24 (continued) for (int index = 0; index > tempHours; hours.push_back(tempHours); // Add an element to hours cout > tempRate; payRate.push_back(tempRate); // Add an element to payRate } cout << "Here is the gross pay for each employee:\n"; cout.precision(2); cout.setf(ios::fixed | ios::showpoint); for (index = 0; index < numEmployees; index++) { float grossPay = hours[index] * payRate[index]; cout << "Employee #" << (index + 1); cout << ": $" << grossPay << endl; } return 0; }

Starting Out with C++, 3 rd Edition 17 Determining the Size of a vector Unlike arrays, vectors can report the number of elements they contain. This is accomplished with the size member function. Here is an example of a statement that uses the size member function: numValues = set.size(); In the statement above, assume that numValues is an int, and set is a vector. After the statement executes, numValues will contain the number of elements in the vector set.

Starting Out with C++, 3 rd Edition 18 Determining the Size of a vector Example: void showValues(vector vect) { for (int count = 0; count < vect.size(); count++) cout << vect[count] << endl; }

Starting Out with C++, 3 rd Edition 19 Program 7-25 // This program demonstrates the vector size // member function. #include using namespace std; #include using namespace std; // Function prototype void showValues(vector ); int main() { vector values; for (int count = 0; count < 7; count++) values.push_back(count * 2); showValues(values); return 0; }

Starting Out with C++, 3 rd Edition 20 Program 7-25 (continued) //************************************************** // Definition of function showValues. * // This function accepts an int vector as its * // argument. The value of each of the vector's * // elements is displayed. * //************************************************** void showValues(vector vect) { for (int count = 0; count < vect.size(); count++) cout << vect[count] << endl; }

Starting Out with C++, 3 rd Edition 21 Program 7-25 (continued) Program Output

Starting Out with C++, 3 rd Edition 22 Removing Elements from a vector Use the pop_back member function to remove the last element from a vector. collection.pop_back(); The statement above removes the last element from the collection vector.

Starting Out with C++, 3 rd Edition 23 Program 7-26 // This program demosntrates the vector size member function. #include using namespace std; #include using namespace std; int main() { vector values; // Store values in the vector values.push_back(1); values.push_back(2); values.push_back(3); cout << "The size of values is " << values.size() << endl; // Remove a value from the vector cout << "Popping a value from the vector...\n"; values.pop_back(); cout << "The size of values is now " << values.size() << endl;

Starting Out with C++, 3 rd Edition 24 Program 7-26 (continued) // Now remove another value from the vector cout << "Popping a value from the vector...\n"; values.pop_back(); cout << "The size of values is now " << values.size() << endl; // Remove the last value from the vector cout << "Popping a value from the vector...\n"; values.pop_back(); cout << "The size of values is now " << values.size() << endl; return 0; } Program Output The size of values is 3 Popping a value from the vector... The size of values is now 2 Popping a value from the vector... The size of values is now 1 Popping a value from the vector... The size of values is now 0

Starting Out with C++, 3 rd Edition 25 Clearing a vector To completely clear the contents of a vector, use the clear member function. Here is an example: numbers.clear(); After the statement above executes, the numbers vector will be cleared of all its elements.

Starting Out with C++, 3 rd Edition 26 Program 7-27 // This program demosntrates the vector size member function. #include using namespace std; #include using namespace std; int main() { vector values(100); cout << "The values vector has “ << values.size() << " elements.\n"; cout << "I will call the clear member function...\n"; values.clear(); cout << "Now, the values vector has “ << values.size() << " elements.\n"; return 0; }

Starting Out with C++, 3 rd Edition 27 Program 7-27 (continued) Program Output The values vector has 100 elements. I will call the clear member function... Now, the values vector has 0 elements.

Starting Out with C++, 3 rd Edition 28 Detecting an Empty vector To determine if a vector is empty, use the empty member function. The function returns true if the vector is empty, and false if the vector has elements stored in it. Here is an example of its use: if (set.empty()) cout << "No values in set.\n";

Starting Out with C++, 3 rd Edition 29 Program 7-28 // This program demonstrates the vector's empty member function. #include using namespace std; #include using namespace std; // Function prototype float avgVector(vector ); int main() { vector values; int numValues; float average; cout > numValues;

Starting Out with C++, 3 rd Edition 30 Program 7-28 (continued) for (int count = 0; count > tempValue; values.push_back(tempValue); } average = avgVector(values); cout << "Average: " << average << endl; return 0; } //************************************************************* // Definition of function avgVector. * // This function accepts an int vector as its argument. If * // the vector contains values, the function returns the * // average of those values. Otherwise, an error message is * // displayed and the function returns 0.0. * //*************************************************************

Starting Out with C++, 3 rd Edition 31 Program 7-28 (continued) float avgVector(vector vect) { int total = 0;// accumulator float avg;// average if (vect.empty())// Determine if the vector is empty { cout << "No values to average.\n"; avg = 0.0; } else { for (int count = 0; count < vect.size(); count++) total += vect[count]; avg = total / vect.size(); } return avg; }

Starting Out with C++, 3 rd Edition 32 Program 7-28 (continued) Program Output with Example Input Shown in Bold How many values do you wish to average? Enter a value: 12 Enter a value: 18 Enter a value: 3 Enter a value: 7 Enter a value: 9 Average: 9 Program Output with Example Input Shown in Bold How many values do you wish to average? 0 No values to average. Average: 0

Starting Out with C++, 3 rd Edition 33 Summary of vector Member Functions Member FunctionDescription at(element) Returns the value of the element located at element in the vector. Example: x = vect.at(5); The statement above assigns the value of the 5 th element of vect to x. capacity() Returns the maximum number of elements that may be stored in the vector without additional memory being allocated. (This is not the same value as returned by the size member function). Example: x = vect.capacity(); The statement above assigns the capacity of vect to x.

Starting Out with C++, 3 rd Edition 34 Summary of vector Member Functions clear() Clears a vector of all its elements. Example: vect.clear(); The statement above removes all the elements from vect. empty() Returns true if the vector is empty. Otherwise, it returns false. Example: if (vect.empty()) cout << "The vector is empty."; The statement above displays the message if vect is empty. pop_back() Removes the last element from the vector. Example: vect.pop_back(); The statement above removes the last element of vect, thus reducing its size by 1.

Starting Out with C++, 3 rd Edition 35 Summary of vector Member Functions push_back(value) Stores a value in the last element of the vector. If the vector is full or empty, a new element is created. Example: vect.push_back(7); The statement above stores 7 in the last element of vect. reverse() Reverses the order of the elements in the vector (the last element becomes the first element, and the first element becomes the last element.) Example: vect.reverse(); The statement above reverses the order of the element in vect. resize(elements, value) Resizes a vector by elements elements. Each of the new elements is initialized with the value in value. Example: vect.resize(5, 1); The statement above increases the size of vect by 5 elements. The 5 new elements are initialized to the value 1.

Starting Out with C++, 3 rd Edition 36 Summary of vector Member Functions swap(vector2) Swaps the contents of the vector with the contents of vector2. Example: vect1.swap(vect2); The statement above swaps the contents of vect1 and vect2.