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

Similar documents
CS 103 Unit 12 Slides

STL. Prof Tejada Week 14

CS 103 Unit 15. Doubly-Linked Lists and Deques. Mark Redekopp

EE 355 Unit 11b. Doubly-Linked Lists and Deques. Mark Redekopp

CSCI 104 Templates. Mark Redekopp David Kempe

CSCI 104 Templates. Mark Redekopp David Kempe

CSCI 104 Overview. Mark Redekopp David Kempe

CSCI 104 C++ STL; Iterators, Maps, Sets. Mark Redekopp David Kempe

EE 355 Unit 13 C++ STL; Iterators, Maps, Sets. Mark Redekopp

CSCI 104 C++ STL; Iterators, Maps, Sets. Mark Redekopp David Kempe

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

CS 103 Unit 11. Linked Lists. Mark Redekopp

1. The term STL stands for?

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

Chapter 17: Linked Lists

CS 103 Unit 13 Slides

CS197c: Programming in C++

Queue Implementations

Exercise 6.2 A generic container class

CSCI 104 Classes. Mark Redekopp David Kempe

SSE2034: System Software Experiment 3

CS 103 Unit 11. Linked Lists. Mark Redekopp

Standard Template Library

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

COEN244: Class & function templates

STL: C++ Standard Library

Chapter 17: Linked Lists

Lectures 11,12. Online documentation & links

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

What will happen if we try to compile, link and run this program? Do you have any comments to the code?

Using the EE 109 Tools. Allan Weber Mark Redekopp

19.1 The Standard Template Library

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

Lab 2: ADT Design & Implementation

CSCI-1200 Data Structures Fall 2010 Lecture 8 Iterators

Templates and Vectors

CSCI-1200 Data Structures Fall 2018 Lecture 7 Templated Classes & Vector Implementation

1 Short Answer (7 Points Each)

Associative Containers and Iterators. Ali Malik

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

CSCI-1200 Data Structures Fall 2014 Lecture 8 Iterators

COP4530 Data Structures, Algorithms and Generic Programming Recitation 4 Date: September 14/18-, 2008

Lesson 13 - Vectors Dynamic Data Storage

CSCI-1200 Data Structures Spring 2018 Lecture 8 Templated Classes & Vector Implementation

C++ Programming. Classes, Constructors, Operator overloading (Continued) M1 Math Michail Lampis

PIC 10A Objects/Classes

Dynamic Data Structures

C++ 프로그래밍실습. Visual Studio Smart Computing Laboratory

CSI33 Data Structures

Linked Lists. Linked list: a collection of items (nodes) containing two components: Data Address (link) of the next node in the list

Linked Lists. Linked list: a collection of items (nodes) containing two components: Data Address (link) of the next node in the list

Introducing C++ to Java Programmers

Programming C++ Lecture 2. Howest, Fall 2014 Instructor: Dr. Jennifer B. Sartor

CSCE 110 PROGRAMMING FUNDAMENTALS

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

CE221 Programming in C++ Part 1 Introduction

CSCI 101L - Data Structures. Practice problems for Final Exam. Instructor: Prof Tejada

Simulations. buffer of fixed capacity using the STL deque. modeling arrival times generating and processing jobs

Patterns: Working with Arrays

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

CSCI 104 Polymorphism. Mark Redekopp David Kempe

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

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

Concurrent Data Structures in C++ CSInParallel Project

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

Implementing an ADT with a Class

CS 211 Winter 2004 Sample Final Exam (Solutions)

Lecture on pointers, references, and arrays and vectors

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

Exception Namespaces C Interoperability Templates. More C++ David Chisnall. March 17, 2011

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

pointers & references

CS93SI Handout 04 Spring 2006 Apr Review Answers

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

General Advise: Don t reinvent the wheel

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

C++ Lab 04 - File I/O, Arrays and Vectors

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

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

Lab 1: First Steps in C++ - Eclipse

Programming Abstractions

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

Chapter 1: Object-Oriented Programming Using C++

Computational Physics

COSC 320 Exam 2 Key Spring Part 1: Hash Functions

Short Notes of CS201

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

CS201 - Introduction to Programming Glossary By

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

DATA STRUCTURES AND ALGORITHMS LECTURE 08 QUEUES IMRAN IHSAN ASSISTANT PROFESSOR AIR UNIVERSITY, ISLAMABAD

CSCI 104 Memory Allocation. Mark Redekopp David Kempe

ECE 462 Exam 1. 6:30-7:30PM, September 22, 2010

Operator overloading

C++ Primer for CS175

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

G52CPP C++ Programming Lecture 18. Dr Jason Atkin

CSCI-1200 Computer Science II Spring 2006 Test 3 Practice Problem Solutions

A brief introduction to C++

Exercise 1.1 Hello world

Chapter 16. Templates. Copyright 2010 Pearson Addison-Wesley. All rights reserved

Transcription:

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

2 Templates We ve built a list to store integers But what if we want a list of double s or char s or other objects We would have to define the same code but with different types What a waste! Enter C++ Templates Allows the one set of code to work for any type the programmer wants struct IntItem int val; IntItem *next; ; class ListInt public: ListInt(); // Constructor ~ListInt(); // Destructor void push_back(int newval);... private: IntItem *head; ; struct DoubleItem double val; DoubleItem *next; ; class ListDouble public: ListDouble(); // Constructor ~ListDouble(); // Destructor void push_back(double newval);... private: DoubleItem *head; ;

3 Templates Enter C++ Templates Allows the type of variable to be a parameter specified by the programmer Compiler will generate separate class/struct code versions for any type desired (i.e instantiated as an object) List<int> my_int_list causes an int version of the code to be generated by the compiler List<double> my_dbl_list causes a double version of the code to be generated by the compiler // declaring templatized code template <typename T> struct Item T val; Item<T> *next; ; template <typename T> class List public: List(); // Constructor ~List(); // Destructor void push_back(t newval);... private: Item<T> *head; ; // Using templatized code // (instantiating templatized objects) int main() List<int> my_int_list(); List<double> my_dbl_list(); my_int_list.push_back(5); my_dbl_list.push_back(5.5125); double x = my_dbl_list.pop_front(); int y = my_int_list.pop_front(); return 0;

4 C++ STL C++ has defined a whole set of templatized classes for you to use out of the box Known as the Standard Template Library (STL)

5 Vector Class 1 2 3 4 Container class (what it contains is up to you via a template) Mimics an array where we have an indexed set of homogenous objects Resizes automatically my_vec my_vec my_vec my_vec 0 1 2 3 4 50 51 52 53 54 0 1 2 3 4 30 5 6 51 52 53 54 10 8 0 1 2 3 4 5 30 51 52 53 54 0 1 2 3 4 30 43 51 53 54 10 5 10 1 2 3 4 #include <iostream> #include <vector> using namespace std; int main() vector<int> my_vec(5); // init. size of 5 for(unsigned int i=0; i < 5; i++) my_vec[i] = i+50; my_vec.push_back(10); my_vec.push_back(8); my_vec[0] = 30; unsigned int i; for(i=0; i < my_vec.size(); i++) cout << my_vec[i] << " "; cout << endl; int x = my_vec.back(); // gets back val. x += my_vec.front(); // gets front val. // x is now 38; cout << "x is " << x << endl; my_vec.pop_back(); my_vec.erase(my_vec.begin() + 2); my_vec.insert(my_vec.begin() + 1, 43); return 0;

6 Vector Class constructor Can pass an initial number of items or leave blank operator[ ] Allows array style indexed access (e.g. myvec[i]) push_back(t new_val) Adds a copy of new_val to the end of the array allocating more memory if necessary size(), empty() Size returns the current number of items stored as an unsigned int Empty returns True if no items in the vector pop_back() Removes the item at the back of the vector (does not return it) front(), back() Return item at front or back erase(index) Removes item at specified index (use begin() + index) insert(index, T new_val) Adds new_val at specified index (use begin() + index) #include <iostream> #include <vector> using namespace std; int main() vector<int> my_vec(5); // 5= init. size for(unsigned int i=0; i < 5; i++) my_vec[i] = i+50; my_vec.push_back(10); my_vec.push_back(8); my_vec[0] = 30; for(int i=0; i < my_vec.size(); i++) cout << my_vec[i] << " "; cout << endl; int x = my_vec.back(); // gets back val. x += my_vec.front(); // gets front val. // x is now 38; cout << "x is " << x << endl; my_vec.pop_back(); my_vec.erase(my_vec.begin() + 2); my_vec.insert(my_vec.begin() + 1, 43); return 0;

7 Exercises http://bits.usc.edu/websheets/?group=vectors vector_eg middle concat parity_counts rpn vector_test

8 Vector Suggestions If you don t provide an initial size to the vector, you must add items using push_back() When iterating over the items with a for loop, use an 'unsigned int' When adding an item, a copy will be made to add to the vector #include <iostream> #include <vector> using namespace std; int main() vector<int> my_vec; for(int i=0; i < 5; i++) // my_vec[i] = i+50; // doesn t work my_vec.push_back(i+50); for(unsigned int i=0; i < my_vec.size(); i++) cout << my_vec[i] << " " cout << endl; do_something(myvec); // copy of myvec passed return 0; void do_something(vector<int> v) // process v;

9 Understanding Performance Vectors are good at some things and worse at others in terms of performance The Good: Fast access for random access (i.e. indexed access such as myvec[6]) Allows for fast addition or removal of items at the back of the vector The Bad: Erasing / removing item at the front or in the middle (it will have to copy all items behind the removed item to the previous slot) Adding too many items (vector allocates more memory that needed to be used for additional push_back() s but when you exceed that size it will be forced to allocate a whole new block of memory and copy over every item After deleting we have to move everyone up 0 1 2 3 4 5 30 51 52 53 54 30 51 52 53 54 10 10 30 51 52 53 54 10 12 18 30 51 52 53 54 10 12 18 Vector may have 1 extra slot, but when we add 2 items a whole new block of memory must be allocated and items copied over

10 Deque Class Double-ended queues (like their name sounds) allow for additions and removals from either end of the list/queue Performance: Slightly slower at random access (i.e. array style indexing access such as: data[3]) than vector Fast at adding or removing items at front or back

11 Deque Class Similar to vector but allows for push_front() and pop_front() options Useful when we want to put things in one end of the list and take them out of the other 1 #include <iostream> #include <deque> using namespace std; int main() deque<int> my_deq; for(int i=0; i < 5; i++) my_deq.push_back(i+50); cout << At index 2 is: << my_deq[2] ; cout << endl; 1 2 3 my_deq my_deq my_deq 0 1 2 3 4 50 51 52 53 54 0 1 2 3 4 51 52 53 54 60 0 1 2 3 4 60 61 62 63 64 after 1 st iteration after all iterations 2 3 4 for(int i=0; i < 5; i++) int x = my_deq.front(); my_deq.push_back(x+10); my_deq.pop_front(); while(! my_deq.empty()) cout << my_deq.front() << ; my_deq.pop_front(); cout << endl; 4 my_deq

ITERATORS 12

13 Iterators Vectors and deques (and other STL container classes to be discussed later) give the programmer the appearance that items are located contiguously in memory (like an array) though in implementation they may not Vectors and deques allow us to use array-like indexing ( myvec[i] ) and finds the correct data behind-the-scenes To iterate over the whole set of items we could use a counter variable and the array indexing ( myvec[i] ), but it can be more efficient (based on how STL is actually implemented) to keep an internal pointer to the next item and update it appropriately C++ STL containers define helper classes called iterators that help iterate over each item or find an item in the container

14 Iterators Iterators are a new class type defined in the scope of each container Initialize them with objname.begin(), check whether they are finished by comparing with objname.end(), and move to the next item with ++ operator #include <iostream> #include <vector> using namespace std; int main() vector<int> my_vec(5); // 5 = init. size for(int i=0; i < 5; i++) my_vec.push_back(i+50); vector<int>::iterator it for(it = myvec.begin() ; it < my_vec.end(); it++)... // vector.h template<class T> class vector class iterator ;

15 Iterators Iterator variable has same semantics as a pointer to an item in the container Use * to dereference and get the actual item #include <iostream> #include <vector> using namespace std; int main() vector<int> my_vec(5); // 5 = init. size for(int i=0; i < 5; i++) my_vec.push_back(i+50); for(vector<int>::iterator it = myvec.begin() ; it!= my_vec.end(); ++it) cout << (*it) cout << endl; return 0;

16 Iterator Tips Think of an iterator variable as a pointer when you declare it, it points at nothing Think of begin() as returning the address of the first item and assigning that to the iterator Think of end() as returning the address AFTER the last item (i.e. off the end of the collection) so that as long as the iterator is less than that, you are safe

CONDITIONAL COMPILATION 17

18 Multiple Inclusion Often multiple file compilation will require #include's of the same file This may cause compiling errors when a duplicate declaration is encountered See example Would like a way to include only once and if another attempt to include is encountered, ignore it class Image... ; #include "Image.h" class Character public: Image *img; ; Image.h Character.h #include "Image.h" #include "Character.h" int main() main.cpp class Image // inc. from Image.h ; class Image // inc. from Character.h ; class Character... int main() main.cpp after preprocessing

19 Conditional Compiler Directives Compiler directives start with '#' define XXX Sets a flag named XXX in the compiler #ifdef, #ifndef XXX #endif Continue compiling code below until #endif, if XXX is (is not) defined Encapsulate header declarations inside a #ifndef XX #define XX #endif #ifndef IMAGE_H #define IMAGE_H class Image... ; #endif #include "Image.h" class Character public: Image *img; ; Image.h Character.h #include "Image.h" #include "Character.h" main.cpp class Image // inc. from Image.h ; class Character // inc. from Character.h... main.cpp after preprocessing

20 Conditional Compilation Often used to compile additional DEBUG code Place code that is only needed for debugging and that you would not want to execute in a release version Place code in a #ifdef XX...#endif bracket Compiler will only compile if a #define XX is found Can specify #define in: source code At compiler command line with (-Dxx) flag g++ -o stuff Ddebug stuff.cpp int main() int x, sum=0, data[10];... for(int i=0; i < 10; i++) sum += data[i]; #ifdef DEBUG cout << "Current sum is "; cout << sum << endl; #endif cout << "Total sum is "; cout << sum << endl; stuff.cpp > g++ -o stuff DDEBUG stuff.cpp