CS193D Handout 12 Winter 2005/2006 January 30, 2006 Introduction to Templates and The STL

Similar documents
Creating Templates and Implementing Smart Pointers CS193D 2/27/06

CS193D Handout 10 Winter 2005/2006 January 23, 2006 Pimp Your Classes

CSI33 Data Structures

Program template-smart-pointers-again.cc

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

Templates and Vectors

Lesson 13 - Vectors Dynamic Data Storage

G52CPP C++ Programming Lecture 18. Dr Jason Atkin

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

Program template-smart-pointers.cc

G52CPP C++ Programming Lecture 18

STL: C++ Standard Library

The Standard Template Library. An introduction

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

19.1 The Standard Template Library

COEN244: Class & function templates

CS 103 Unit 12 Slides

THE STANDARD TEMPLATE LIBRARY (STL) Week 6 BITE 1513 Computer Game Programming

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

Function Templates. Consider the following function:

#include <iostream> #include <algorithm> #include <cmath> using namespace std; int f1(int x, int y) { return (double)(x/y); }

Due Date: See Blackboard

Exam duration: 3 hours Number of pages: 10

Module 9. Templates & STL

Lecture-5. STL Containers & Iterators

1 Unit 8 'for' Loops

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

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms

More About Classes. Gaddis Ch. 14, CS 2308 :: Fall 2015 Molly O'Neil

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

Linked List using a Sentinel

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak!

Programming with Haiku

Assignment 1: grid. Due November 20, 11:59 PM Introduction

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

Tell compiler ValueType is a generic type. public: void push_back(const ValueType& elem); // rest of implementation }

When we program, we have to deal with errors. Our most basic aim is correctness, but we must

Wentworth Institute of Technology COMP201 Computer Science II Spring 2015 Derbinsky. C++ Kitchen Sink. Lecture 14.

CSC1322 Object-Oriented Programming Concepts

CS197c: Programming in C++

Lecture on pointers, references, and arrays and vectors

STL Standard Template Library

STL Containers, Part II

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

Tell compiler ValueType is a generic type. public: void push_back(const ValueType& elem); // rest of implementation }

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

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

1. The term STL stands for?

Pointers II. Class 31

Lab 1: First Steps in C++ - Eclipse

Outline. Variables Automatic type inference. Generic programming. Generic programming. Templates Template compilation

EL2310 Scientific Programming

Short Notes of CS201

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

CS201 - Introduction to Programming Glossary By

Lecture 2, September 4

Introduction to Programming using C++

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

The Standard Template Library Classes

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

DYNAMIC ARRAYS; FUNCTIONS & POINTERS; SHALLOW VS DEEP COPY

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8

CSS 342 Data Structures, Algorithms, and Discrete Mathematics I. Standard Template Library

7 TEMPLATES AND STL. 7.1 Function Templates

CE221 Programming in C++ Part 1 Introduction

BEng (Hons) Electronic Engineering. Resit Examinations for / Semester 1

CPSC 427a: Object-Oriented Programming

Problem Set 1. You might want to read Chapter 12 of the course reader before attempting this problem.

Fundamentals of Type-Dependent Code Reuse in C++ Mark Isaacson

CSE au Midterm Exam Nov. 2, 2018 Sample Solution

The University of Nottingham

Today. andyoucanalsoconsultchapters6amd7inthetextbook. cis15-fall2007-parsons-lectvii.1 2

C++ Programming Lecture 2 Software Engineering Group

GCC : From 2.95 to 3.2

C++ Namespaces, Exceptions

Semantics of C++ Hauptseminar im Wintersemester 2009/10 Templates

Programmazione. Prof. Marco Bertini

W3101: Programming Languages C++ Ramana Isukapalli

Programming in C++: Assignment Week 8

Programming Abstractions

Midterm Practice Exam

Container Notes. Di erent Kinds of Containers. Types Defined by Containers. C++11 Container Notes C++11

ECE 462 Fall 2011, Third Exam

Pointers, Dynamic Data, and Reference Types

CS

EE 355 Unit 10. C++ STL - Vectors and Deques. Mark Redekopp

Where do we go from here?

CSE 333 Lecture 9 - intro to C++

Lab 8. Follow along with your TA as they demo GDB. Make sure you understand all of the commands, how and when to use them.

377 Student Guide to C++

TEMPLATE IN C++ Function Templates

Dynamic Data Structures

Overview. 1. Expression Value Categories 2. Rvalue References 3. Templates 4. Miscellaneous Hilarity 2/43

SSE2034: System Software Experiment 3

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

CS24 Week 3 Lecture 1

CS2141 Software Development using C/C++ C++ Basics

CS93SI Handout 04 Spring 2006 Apr Review Answers

Variables, Memory and Pointers

Managing Memory. (and low level Data Structures) Lectures 22, 23. Hartmut Kaiser.

Transcription:

CS193D Handout 12 Winter 2005/2006 January 30, 2006 Introduction to Templates and The STL See also: Chapter 4 (89-100), Chapter 11 (279-281), and Chapter 21 // GameBoard.h class GameBoard { public: // The general-purpose GameBoard allows the user to specify its dimensions GameBoard(int inwidth, int inheight); GameBoard(const GameBoard& src); // Copy constructor ~GameBoard(); GameBoard &operator=(const GameBoard& rhs); // Assignment operator void setpieceat(int x, int y, const GamePiece& inpiece); GamePiece& getpieceat(int x, int y); const GamePiece& getpieceat(int x, int y) const; int getheight() const { return mheight; int getwidth() const { return mwidth; protected: void copyfrom(const GameBoard& src); // Objects dynamically allocate space for the game pieces. GamePiece** mcells; int mwidth, mheight;

;

Templates Strengths Weaknesses Type Safe Compile-Time Checks Easy to Use "Code Bloat" Gross Syntax Always Homogenous

// Grid.h template <typename T> class Grid { public: Grid(int inwidth, int inheight); Grid(const Grid<T>& src); ~Grid(); Grid<T>& operator=(const Grid<T>& rhs); void setelementat(int x, int y, const T& inelem); T& getelementat(int x, int y); const T& getelementat(int x, int y) const; int getheight() const { return mheight; int getwidth() const { return mwidth; static const int kdefaultwidth = 10; static const int kdefaultheight = 10; ; protected: void copyfrom(const Grid<T>& src); T** mcells; int mwidth, mheight;

Grid<int> myintgrid(5, 5); // Declares a 5x5 grid that stores ints myintgrid.setelementat(0, 0, 10); int x = myintgrid.getelementat(0, 0); Grid<int> grid2(myintgrid); Grid<SpreadsheetCell> myspreadsheet(10, 10); SpreadsheetCell mycell; myspreadsheet.setelementat(3, 4, mycell); Grid<char*> mystringgrid(2, 2); mystringgrid.setelementat(2, 2, "hello"); Grid<Grid<int> > mygridofgrids(3, 3); mygridofgrids.setelementat(0, 1, myintgrid);

myintgrid = mystringgrid; // BUG! They're different types! void foo(grid<int>& ingridbergman); // The template type is part of the type Selective Instantiation: If your class doesn't support features that the template class uses, those parts of the template class will be omitted.

The Standard Template Library (STL) Strengths Standardized Flexible Comprehensive Helps Avoid Dynamic Memory Extensible Weaknesses Steep Learning Curve Gross Syntax Heavyweight Not Thread Safe Strange Omissions Often Chokes on References Hard to Extend A good abstraction makes the common case easy and the rare case possible.

STL Containers vector list deque stack queue map multimap set multiset

STL Algorithms Generic way of performing a task STL Iterators Objects for accessing elements of a container. Each STL container has a corresponding iterator.

#include <vector> #include <iostream> using namespace std; int main(int argc, char** argv) { vector<double> doublevector(10, 0); // Create a vector of 10 doubles, initialized to 0 double max; cout << "Enter score 1: "; cin >> doublevector[0]; max = doublevector[0]; for (int i = 1; i < 10; i++) { cout << "Enter score " << i + 1 << ": "; cin >> doublevector[i]; if (doublevector[i] > max) { max = doublevector[i]; max /= 100; for (int i = 0; i < 10; i++) { doublevector[i] /= max; cout << doublevector[i] << " "; cout << endl;

int main(int argc, char** argv) { vector<double> doublevector; // Create a vector with zero elements. double max, temp; size_t i; cout << "Enter score 1: "; cin >> max; doublevector.push_back(max); for (i = 1; true; i++) { cout << "Enter score " << i + 1 << " (-1 to stop): "; cin >> temp; if (temp == -1) { break; doublevector.push_back(temp); if (temp > max) { max = temp; max /= 100; for (i = 0; i < doublevector.size(); i++) { doublevector[i] /= max; cout << doublevector[i] << " "; cout << endl;

class Element { public: Element() { ~Element() { ; int main(int argc, char** argv) { vector<element> elementvector; Element e1; elementvector.push_back(e1);

Working with vectors // vectors on the heap vector<element>* elementvector = new vector<element>(10); delete elementvector; // reusing a vector vector<int> intvector(10, 0); // Other code... intvector.assign(5, 100); // comparing vectors if (vectorone == vectortwo) { cout << "equal!\n"; else { cout << "not equal!\n"; See reference for other vector methods

vector Iterators for (i = 0; i < doublevector.size(); i++) { doublevector[i] /= max; cout << doublevector[i] << " "; for (vector<double>::iterator it = doublevector.begin(); it!= doublevector.end(); ++it) { *it /= max; cout << *it << " "; -> works with iterators: for (vector<scell>::iterator it = sheet.begin(); it!= sheet.end(); it++) { cout << it->getvalue(); << endl;

const iterators: vector<type>::const_iterator it = myvector.begin(); Why use iterators? They indicate positions and ranges: vector<int> vectorone, vectortwo; int i; vectorone.push_back(1); vectorone.push_back(2); vectorone.push_back(3); vectorone.push_back(5); // Oops, we forgot to add 4. Insert it in the correct place. vectorone.insert(vectorone.begin() + 3, 4);

// Add elements 6 through 10 to vectortwo. for (i = 6; i <= 10; i++) { vectortwo.push_back(i); // Add all the elements from vectortwo to the end of vectorone. vectorone.insert(vectorone.end(), vectortwo.begin(), vectortwo.end()); // Clear vectortwo entirely. vectortwo.clear(); // And add 10 copies of the value 100. vectortwo.insert(vectortwo.begin(), 10, 100); // Decide we only want 9 elements. vectortwo.pop_back(); // Now erase the numbers 2 through 5 in vectorone. vectorone.erase(vectorone.begin() + 1, vectorone.begin() + 5);

Associative Containers A container that stores keys and values instead of ordered elements Examples: map multimap set multiset

The pair Class #include <utility> #include <string> #include <iostream> using namespace std; int main(int argc, char** argv) { pair<string, int> mypair("hello", 5), myotherpair; myotherpair.first = "hello"; myotherpair.second = 6; pair<string, int> mythirdpair(myotherpair); if (mypair < myotherpair) { cout << "mypair is less than myotherpair\n"; else { cout << "mypair is greater than or equal to myotherpair\n"; if (myotherpair == mythirdpair) { cout << "myotherpair is equal to mythirdpair\n"; else { cout << "myotherpair is not equal to mythirdpair\n";

make_pair function pair<int, int> apair = make_pair(5, 10); void foo(pair<int, int> inpair); int main() { pair<int, int> mypair(5, 10); foo(mypair); foo(make_pair(5, 10)); // shortcut using make_pair()

#include <map> using namespace std; class Data { public: Data(int val) { mval = val; int getval() const { return mval; void setval(int val) {mval = val; // Remainder of definition omitted protected: int mval; ; int main(int argc, char** argv) { map<int, Data> datamap;

Forget insert(), use [] datamap[1] = Data(4); datamap[1] = Data(6); // Replaces the element with key 1 Even with non-ints: map<string, string> namemap; namemap["kleper"] = "Scott"; Map iterator: for (map<int, Data>::iterator it = datamap.begin(); it!= datamap.end(); ++it) { cout << it->second.getval() << endl;

Getting values out of a map by key: cout << "First name of Kleper is " << namemap["kleper"] << endl; // Previous line will insert key "Kleper" if it doesn't exist! To lookup a value without possibility of adding a new one, use find() with an iterator: map<string, string>::iterator it = namemap.find("kleper"); if (it!= datamap.end()) { cout << "First name of Kleper is " << it->second; To remove an element, use erase() cout << "There are " << namemap.count("kleper") << " Klepers\n"; namemap.erase("kleper"); cout << "There are " << namemap.count("kleper") << " Klepers\n";