Containers in C++ and Java

Size: px
Start display at page:

Download "Containers in C++ and Java"

Transcription

1 Containers in C++ and Java 1

2 1. Which of the following statements is true? a) Equality on the basis of reference implies equality on the basis of content. b) Equality on the basis of content implies equality on the basis of reference. 2

3 2. Consider the following two Java program fragments with two variables s1 and s2 holding references to the String objects as shown: String s1 = new String( "hello" ); String s1 = "hello"; String s2 = new String( "hello" ); String s2 = "hello"; Is s1 == s2 true? Is s1 == s2 true? Give reasons for your answser. 3

4 3. Java says to use the method equals() to test strings for equality of content. In which case below would this work? CASE 1: String s1 = new String( "Hello" ); String s2 = new String( "Hello" ); System.out.println( ( s1.equals( s2 ) ) + "" ); //??? CASE 2: StringBuffer s3 = new StringBuffer( "Hello" ); StringBuffer s4 = new StringBuffer( "Hello" ); System.out.println( ( s3.equals( s4 ) ) + "" ); //??? 4

5 4. In general, Java does not allow for operator overloading. There is only one exception to this rule. Which operator and for what type? 5

6 5. Since the operator + has not been overloaded for the StringBuffer type, how would you join two StringBuffer strings? 6

7 6. In general, suppose I define a class X in Java class X { } and construct two objects x1 and x2 of type X. Will there be any difference between what is returned by and by x1 == x2 x1.equals( x2 ) 7

8 7. Now that you have gained some insights into the class string in C++, do you see why you need to have private data members in a class? 8

9 Container Classes What are the two most widely used containers for holding together multiple items of data in a majority of programming languages? 9

10 Arrays Linked Lists 10

11 But for heavy-duty programming, both arrays and linked lists suffer from limitations. What are these limitations? 11

12 The container classes that are a part of the C++ Standard Template Library (STL) and those that come with the Java Collections Framework are designed to fix the shortcomings of plain arrays and linked lists. 12

13 In addition to the container classes, the C++ Standard Template Library and the Java Collections Framework also contain support for various algorithms that can be used with the containers for sorting, searching, inserting, deleting, shuffling, etc. 13

14 C++ Containers STL consists of the following ten main container classes: vector list deque stack queue priority queue map set multimap and multiset 14

15 Sequence Containers vector: Particularly efficient for random access of data elements using array like indexing. list: Particularly efficient for all kinds of list operations, meaning insertion and deletion of elements anywhere in a list, including the addition and deletion of elements at both its ends. deque: Combines the best of vector and list with regard to subscripting via the [] operator and the add/delete operations at both ends of a data sequence stored in a deque. 15

16 Operation vector deque list Efficiency for array-like access O(1) O(1) O(N) Efficiency for insert/delete at front O(N) O(1)+ O(1) Efficiency for insert/delete at back O(1)+ O(1)+ O(1) Efficiency for insert/delete in middle O(N) O(N) O(1) 16

17 Adapters stack: Only supports storage and retrieval at the back end of a sequence of data. That means that the only data element that can be retrieved is the one that was pushed most recently into the stack. queue: Only supports storage and retrieval at the front end of a sequence of data. That means that the very first data element that was pushed into the queue is the only one that is available for retrieval. priority queue: In a priority queue, the elements are stored in a sorted order on the basis of a priority value associated with each element. 17

18 Associative Containers map: This container is used to store a sequence of (key, value) pairs. set: A set is a degenerate form of a map in that no value need be specified for the keys. Therefore, in contrast with, say, a vector or a list, the list of objects (meaning the keys) is stored in a sorted order. multimap: A more general form of map. multiset: A multiset is a degenerate form of a multimap in which no value need be specified for the keys. 18

19 C++ vector: A vector is like an array that can grow and shrink as elements are added to or removed from the vector Since vectors allow for array-like indexing, they can be used very much like arrays. In addition, since vectors allow new elements to be inserted anywhere, they can be used very much like linked lists. The random access efficiency of a vector through array like indexing is comparable to that for arrays since as for arrays the elements are held in a contiguous block of memory. 19

20 Doesn t holding all the elements of a vector in one contiguous block of memory prevent an indefinite insertion of new elements into the vector? Won t the vector eventually run into the memory allocated to other objects in a computer program? 20

21 In a vector, this problem is taken care of by allowing a vector to migrate elsewhere in memory as further elements are added to the vector. Therefore, it makes no sense to write functions that have pointers to vectors or to vector elements. 21

22 #include <iostream> #include <vector> // (A) void print( vector<int> ); int main() { vector<int> vec; vec.push_back( 34 ); vec.push_back( 23 ); // size is now 2 vector<int>::iterator p; // (B) // (C) // (D) print( vec ); // p = vec.begin(); // (E) *p = 68; // (F) *(p + 1) = 69; // (G) // *(p + 2) = 70; // WRONG // (H) print( vec ); // vec.pop_back(); // size is now 1 // (I) print( vec ); // 68 vec.push_back(101); vec.push_back(103); // (J) // (K) 22

23 // size is now 3 int i = 0; while ( i < vec.size() ) cout << vec[i++] << " "; cout << endl; // vec[0] = 1000; vec[1] = 1001; vec[2] = 1002; // (L) // (M) // (N) // (O) } print( vec ); // void print( vector<int> v ) { cout << "\nvector size is: " << v.size() << endl; vector<int>::iterator p = v.begin(); while ( p!= v.end() ) cout << *p++ << " "; cout << endl << endl; } 23

24 #include <iostream> #include <vector> int sum( vector<int> vec ) { int result = 0; vector<int>::iterator p = vec.begin(); while ( p!= vec.end() ) result += *p++; return result; } int main() { vector<int> v1(100); cout << v1.size() << endl; // 100 cout << sum( v1 ) << endl; // 0 v1.push_back( 23 ); cout << v1.size() << endl; // 101 cout << sum( v1 ) << endl; // 23 v1.reserve( 1000 ); cout << v1.capacity() << endl; // 1000 cout << v1.size() << endl; // 101 cout << v1[900] << endl; // undefined cout << sum( v1 ) << endl; // 23 cout << v1.front() << endl; // 0 cout << v1.back() << endl; // 23 v1.pop_back(); 24

25 cout << v1[ v1.size() - 1 ] << endl; // 0 vector<int>::iterator p = &v1[50]; cout << *p << endl; // 0 vector<int> v2(150, 2); cout << sum( v2 ) << endl; // 300 v2.resize( 500 ); cout << v2.size() << endl; // 500 cout << v2[150] << endl; // 0 v2.clear(); cout << v2.empty() << endl; // true cout << v2.capacity() << endl; // 500 cout << v2.size() << endl; // 0 v2.resize( 0 ); cout << v2.capacity() << endl; // 500 cout << v2.size() << endl; // 0 } return 0; 25

26 List Operations on Vectors A vector can also be used in pretty much the same manner as a linked list, meaning that elements can be added or removed at the beginning, anywhere in the middle, or at the end of a vector. 26

27 #include <iostream> #include <vector> #include <algorithm> // find() and sort() generic functions void print( vector<int> ); int main() { vector<int> vec(5); print( vec ); // vec.insert( vec.begin(), 9 ); print( vec ); // vec.erase( vec.begin() ); print( vec ); // vec.insert( vec.begin() + 2, 8 ); print( vec ); // vec.erase( vec.begin() + 2 ); print( vec ); // vec.insert( vec.end(), 7 ); print( vec ); // vec.erase( vec.end() - 1 ); print( vec ); //

28 vec.insert( vec.begin() + 3, 6 ); print( vec ); // vec.erase( find( vec.begin(), vec.end(), 6 ) ); print( vec ); // vec.insert( vec.begin() + 1, 3 ); vec.insert( vec.begin() + 5, 3 ); print( vec ); // vec.erase( find( vec.begin(), vec.end(), 3 ) ); vec.erase( find( vec.begin(), vec.end(), 3 ) ); print( vec ); // vec[0] = 23; vec[1] = 2; vec[2] = 16; vec[3] = 45; vec[4] = 16; } print( vec ); // sort( vec.begin(), vec.end() ); print( vec ); // void print( vector<int> v ) { vector<int>::iterator p = v.begin(); while ( p!= v.end() ) cout << *p++ << " "; cout << endl; 28

29 } 29

30 #include <iostream> #include <vector> #include <string> #include <algorithm> void print( vector<string> ); int main() { vector<string> vec; vec.push_back( "hi" ); vec.push_back( "wow" ); vec.push_back( "daah" ); vec.push_back( "hello" ); vec.push_back( "zora" ); vec.push_back( "dud" ); vec.push_back( "huh" ); vec.push_back( "yuk" ); print( vec ); sort( vec.begin(), vec.end() ); print( vec ); vec.erase( find( vec.begin(), vec.end(), "yuk" ) ); print( vec ); vec.erase( vec.begin() + 1 ); print( vec ); // (A) // (B) // (C) // (D) 30

31 vec.insert( vec.begin() + 1, "yum" ); print( vec ); vec.insert( vec.end(), "zing" ); // eqiv to vec.push_back(...) print( vec ); // (E) // (F) } void print( vector<string> vec ) { vector<string>::iterator p = vec.begin(); while ( p < vec.end() ) cout << *p++ << " "; cout << endl; } 31

32 Using an Array to Initialize a Vector To initialize a vector with an array, the vector constructor takes two arguments, both pointers, one pointing to the beginning of the array and the other to one past the end of the array. 32

33 #include <iostream> #include <vector> void print( vector<int> ); int main() { int data[] = {11, 12, 23, 34}; int size = sizeof( data ) / sizeof( data[0] ); vector<int> vec( data, &data[ size ] ); // (A) // (B) // (C) } print( vec ); // (D) void print( vector<int> vec ) { vector<int>::iterator p = vec.begin(); while ( p < vec.end() ) cout << *p++ << " "; cout << endl; } 33

34 Vector of Class Type Objects For a class type object to be stored in a container, at the minimum the class should support a no-arg constructor so that memory appropriated for a container can be properly initialized. The class must also possess overload definitions for the == and < operators so that the objects stored in a container can be compared for the various STL algorithms. 34

35 #include <iostream> #include <vector> #include <algorithm> // for sort() class X { int p; public: X() { p = 42; } X( int q ) { p = q; } int getp() const { return p; } }; bool operator<( const X& x1, const X& x2 ) { return x1.getp() < x2.getp(); } bool operator==( const X& x1, const X& x2 ) { return x1.getp() == x2.getp(); } //(A) //(B) void print( vector<x> ); 35

36 int main() { vector<x> vec; X x1( 2 ); X x2( 3 ); X x3( 5 ); vec.push_back( x1 ); vec.push_back( x3 ); vec.push_back( x2 ); print( vec ); // vec.erase( vec.begin(), vec.end() ); print( vec ); // size of vec is 0 cout << x1.getp() << " " << x2.getp() << " " << x3.getp() << endl; // vector<x> vec_2( 5 ); print( vec_2 ); // vec_2.resize( 7 ); print( vec_2 ); // vec_2.reserve( 10 ); cout << vec_2.capacity() << endl; // 10 print( vec_2 ); // , // size still returns 5 cout << vec_2[ 8 ].getp() << endl; // undefined 36

37 vec_2[0] = X(12); vec_2[1] = X(36); vec_2[2] = X(3); vec_2[3] = X(56); vec_2[4] = X(2); sort( vec_2.begin(), vec_2.end() ); //(E) print( vec_2 ); // vec_2.clear(); print( vec_2 ); // vec_2 is now empty cout << vec_2.capacity() << endl; // 10 } return 0; void print( vector<x> v ) { cout << "\nvector size is: " << v.size() << endl; vector<x>::iterator p = v.begin(); while ( p!= v.end() ) cout << (*p++).getp() << " "; cout << endl << endl; } 37

38 Deque A deque has all the functionality of a vector and then some. A vector is inefficient for insert/delete operations at the front of the sequence, because if you insert a new element at the front, you d need to shuffle all the other elements in the memory to their next location. On the other hand, in a deque the insert/delete operations at the front are just as efficient as they are at the back. So, whereas avector provides us with the efficientpush back andpop back operations at the back, a deque has these two and also push front and pop front for equally efficient operations at the front. 38

39 //DequeFront.cc #include <string> #include <deque> #include <algorithm> // for sort, find void print( deque<string> ); int main() { deque<string> animals; animals.push_back( "yak" ); animals.push_back( "zebra" ); animals.push_front( "cat" ); animals.push_front( "canary" ); print(animals); // canary cat yak zebra animals.pop_front(); animals.pop_back(); print(animals); // cat yak animals.erase( find( animals.begin(), animals.end(), "cat" ) ); print(animals); // yak animals.insert( animals.begin(), "canary" ); print(animals); // canray yak 39

40 int sz = animals.size(); // 2 animals.resize( 5 ); // size() will now return 5 animals[sz] = "fox"; animals[sz+1] = "elephant"; animals[sz+2] = "cat"; print( animals ); // animals[2] = "fox" // animals[3] = "elephant" // animals[4] = "cat" // canary yak fox elephant cat animals.erase( animals.begin() + 2 ); // remove "fox" print( animals ); // canary yak elephant cat } sort( animals.begin(), animals.end() ); print( animals ); // canary cat elephant yak void print( deque<string> d ) { typedef deque<string>::const_iterator CI; cout << "The number of items in the deque: " << d.size() << endl;; for ( CI iter = d.begin(); iter!= d.end(); iter++ ) cout << *iter << " "; cout << endl << endl; } 40

41 List If your application requires frequent insertions of new data items anywhere front, back, or anywhere else in the middle in a sequence and array-like indexing for accessing the data items is not important, then you need to use a list. 41

42 #include <string> #include <list> void print( list<string>& ); int main() { list<string> animals; animals.push_back( "cheetah" ); animals.push_back( "lion" ); animals.push_back( "cat" ); animals.push_back( "fox" ); animals.push_back( "elephant" ); animals.push_back( "cat" ); //<<<<< duplicate print( animals ); animals.pop_back(); print( animals ); animals.remove( "lion" ); print( animals ); animals.push_front( "lion" ); print( animals ); animals.pop_front( ); print( animals ); // cheetah lion cat fox elephant cat // cheetah lion cat fox elephant // first occurrence of "lion" // cheetah cat fox elephant // lion cheetah cat fox elephant // cheetah cat fox elephant animals.insert( animals.end(), "cat" ); print( animals ); // cheetah cat fox elephant cat 42

43 animals.sort(); print( animals ); animals.unique(); print( animals ); // cat cat cheetah elephant fox // cat cheetah elephant fox list<string> pets; pets.push_back( "cat" ); pets.push_back( "dog" ); pets.push_back( "turtle" ); pets.push_back( "bird" ); animals.splice( animals.begin(), pets, pets.begin() ); print( animals ); // cat cat cheetah elephant fox print( pets ); // dog turtle bird pets.sort(); // bird dog turtle animals.merge( pets ); } cout << pets.empty() << endl; print( animals ); // true // bird cat cat cheetah dog elephant // fox turtle void print( list<string>& li ) { typedef list<string>::const_iterator CI; 43

44 } cout << "The number of items in the list: " << li.size() << endl;; for ( CI iter = li.begin(); iter!= li.end(); iter++ ) cout << *iter << " "; cout << endl << endl; 44

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

THE STANDARD TEMPLATE LIBRARY (STL) Week 6 BITE 1513 Computer Game Programming THE STANDARD TEMPLATE LIBRARY (STL) Week 6 BITE 1513 Computer Game Programming What the heck is STL???? Another hard to understand and lazy to implement stuff? Standard Template Library The standard template

More information

ECE 462 Midterm Exam 1. 10:30-11:20AM, September 21, 2007

ECE 462 Midterm Exam 1. 10:30-11:20AM, September 21, 2007 ECE 462 Midterm Exam 1 10:30-11:20AM, September 21, 2007 1 Template Classes and the STL Library 1.1 Container Classes Which statement is correct? Answer: B A. An element can be inserted anywhere in a stack.

More information

CS197c: Programming in C++

CS197c: Programming in C++ CS197c: Programming in C++ Lecture 2 Marc Cartright http://ciir.cs.umass.edu/~irmarc/cs197c/index.html Administration HW1 will be up this afternoon Written assignment Due in class next week See website

More information

Function Templates. Consider the following function:

Function Templates. Consider the following function: Function Templates Consider the following function: void swap (int& a, int& b) { int tmp = a; a = b; b = tmp; Swapping integers. This function let's you swap the contents of two integer variables. But

More information

The Standard Template Library Classes

The Standard Template Library Classes The Standard Template Library Classes Lecture 33 Sections 9.7, 9.8 Robb T. Koether Hampden-Sydney College Wed, Apr 23, 2014 Robb T. Koether (Hampden-Sydney College) The Standard Template Library Classes

More information

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

Arrays - Vectors. Arrays: ordered sequence of values of the same type. Structures: named components of various types Arrays - Vectors Data Types Data Type: I. set of values II. set of operations over those values Example: Integer I. whole numbers, -32768 to 32767 II. +, -, *, /, %, ==,!=, , =,... Which operation

More information

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

CSS 342 Data Structures, Algorithms, and Discrete Mathematics I. Standard Template Library CSS 342 Data Structures, Algorithms, and Discrete Mathematics I Standard Template Library 1 Standard Template Library Need to understand basic data types, so we build them ourselves Once understood, we

More information

Standard Template Library

Standard Template Library Standard Template Library The standard template library (STL) contains CONTAINERS ALGORITHMS ITERATORS A container is a way that stored data is organized in memory, for example an array of elements. Algorithms

More information

Dynamic Data Structures

Dynamic Data Structures Dynamic Data Structures We have seen that the STL containers vector, deque, list, set and map can grow and shrink dynamically. We now examine how some of these containers can be implemented in C++. To

More information

CPSC 427a: Object-Oriented Programming

CPSC 427a: Object-Oriented Programming CPSC 427a: Object-Oriented Programming Michael J. Fischer Lecture 17 November 1, 2011 CPSC 427a, Lecture 17 1/21 CPSC 427a, Lecture 17 2/21 CPSC 427a, Lecture 17 3/21 A bit of history C++ standardization.

More information

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

STL components. STL: C++ Standard Library Standard Template Library (STL) Main Ideas. Components. Encapsulates complex data structures and algorithms STL: C++ Standard Library Standard Template Library (STL) Encapsulates complex data structures and algorithms is a library of generic container classes which are both efficient and functional C++ STL developed

More information

STL: C++ Standard Library

STL: C++ Standard Library STL: C++ Standard Library Encapsulates complex data structures and algorithms CSC 330 OO Software Design 1 We ve emphasized the importance of software reuse. Recognizing that many data structures and algorithms

More information

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

Unit 1: Preliminaries Part 4: Introduction to the Standard Template Library Unit 1: Preliminaries Part 4: Introduction to the Standard Template Library Engineering 4892: Data Structures Faculty of Engineering & Applied Science Memorial University of Newfoundland May 6, 2010 ENGI

More information

Standard Template Library. Containers, Iterators, Algorithms. Sequence Containers. Containers

Standard Template Library. Containers, Iterators, Algorithms. Sequence Containers. Containers Standard Template Library The standard template library (STL) contains Containers Algorithms Iterators A container is a way that stored data is organized in memory, for example an array of elements. Algorithms

More information

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

Container Notes. Di erent Kinds of Containers. Types Defined by Containers. C++11 Container Notes C++11 Di erent Kinds of Containers Container Notes A container is an object that stores other objects and has methods for accessing the elements. There are two fundamentally di erent kinds of containers: Sequences

More information

C++ TEMPLATES. Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particular type.

C++ TEMPLATES. Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particular type. C++ TEMPLATES http://www.tutorialspoint.com/cplusplus/cpp_templates.htm Copyright tutorialspoint.com Templates are the foundation of generic programming, which involves writing code in a way that is independent

More information

Lecture on pointers, references, and arrays and vectors

Lecture on pointers, references, and arrays and vectors Lecture on pointers, references, and arrays and vectors pointers for example, check out: http://www.programiz.com/cpp-programming/pointers [the following text is an excerpt of this website] #include

More information

CSCI-1200 Data Structures Fall 2016 Lecture 17 Associative Containers (Maps), Part 2

CSCI-1200 Data Structures Fall 2016 Lecture 17 Associative Containers (Maps), Part 2 CSCI-1200 Data Structures Fall 2016 Lecture 17 Associative Containers (Maps), Part 2 Review of Lecture 16 Maps are associations between keys and values. Maps have fast insert, access and remove operations:

More information

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

Type Aliases. Examples: using newtype = existingtype; // C++11 typedef existingtype newtype; // equivalent, still works Type Aliases A name may be defined as a synonym for an existing type name. Traditionally, typedef is used for this purpose. In the new standard, an alias declaration can also be used C++11.Thetwoformsareequivalent.

More information

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

CSCI-1200 Data Structures Fall 2013 Lecture 9 Iterators & Lists Review from Lecture 8 CSCI-1200 Data Structures Fall 2013 Lecture 9 Iterators & Lists Explored a program to maintain a class enrollment list and an associated waiting list. Unfortunately, erasing items

More information

STL Quick Reference for CS 241

STL Quick Reference for CS 241 STL Quick Reference for CS 241 Spring 2018 The purpose of this document is to provide basic information on those elements of the C++14 standard library we think are most likely to be needed in CS 241.

More information

The Standard Template Library. An introduction

The Standard Template Library. An introduction 1 The Standard Template Library An introduction 2 Standard Template Library (STL) Objective: Reuse common code Common constructs: Generic containers and algorithms STL Part of the C++ Standard Library

More information

General Advise: Don t reinvent the wheel

General Advise: Don t reinvent the wheel General Advise: Don t reinvent the wheel Use libraries: Discover the available open source libraries for your application Examples: STL, boost, thrust libraries Info on C++ and STL: http://www.cplusplus.com/reference,

More information

Templates and Vectors

Templates and Vectors Templates and Vectors 1 Generic Programming function templates class templates 2 the STL vector class a vector of strings enumerating elements with an iterator inserting and erasing 3 Writing our own vector

More information

CS2720 Practical Software Development

CS2720 Practical Software Development Page 1 Rex Forsyth CS2720 Practical Software Development CS2720 Practical Software Development STL Tutorial Spring 2011 Instructor: Rex Forsyth Office: C-558 E-mail: forsyth@cs.uleth.ca Tel: 329-2496 Tutorial

More information

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

Today. andyoucanalsoconsultchapters6amd7inthetextbook. cis15-fall2007-parsons-lectvii.1 2 TEMPLATES Today This lecture looks at techniques for generic programming: Generic pointers Templates The standard template library Thebestreferenceis: http://www.cppreference.com/index.html andyoucanalsoconsultchapters6amd7inthetextbook.

More information

CMSC 341 Lecture 6 STL, Stacks, & Queues. Based on slides by Lupoli, Dixon & Gibson at UMBC

CMSC 341 Lecture 6 STL, Stacks, & Queues. Based on slides by Lupoli, Dixon & Gibson at UMBC CMSC 341 Lecture 6 STL, Stacks, & Queues Based on slides by Lupoli, Dixon & Gibson at UMBC Templates 2 Common Uses for Templates Some common algorithms that easily lend themselves to templates: Swap what

More information

use static size for this buffer

use static size for this buffer Software Design (C++) 4. Templates and standard library (STL) Juha Vihavainen University of Helsinki Overview Introduction to templates (generics) std::vector again templates: specialization by code generation

More information

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

CSCI-1200 Data Structures Spring 2018 Lecture 15 Associative Containers (Maps), Part 2 CSCI-1200 Data Structures Spring 2018 Lecture 15 Associative Containers (Maps), Part 2 Review of Lecture 14 Maps are associations between keys and values. Maps have fast insert, access and remove operations:

More information

STL Standard Template Library

STL Standard Template Library STL Standard Template Library September 22, 2016 CMPE 250 STL Standard Template Library September 22, 2016 1 / 25 STL Standard Template Library Collections of useful classes for common data structures

More information

Chapter 5. The Standard Template Library.

Chapter 5. The Standard Template Library. Object-oriented programming B, Lecture 11e. 1 Chapter 5. The Standard Template Library. 5.1. Overview of main STL components. The Standard Template Library (STL) has been developed by Alexander Stepanov,

More information

Computational Physics

Computational Physics Computational Physics numerical methods with C++ (and UNIX) 2018-19 Fernando Barao Instituto Superior Tecnico, Dep. Fisica email: fernando.barao@tecnico.ulisboa.pt Computational Physics 2018-19 (Phys Dep

More information

PENN STATE UNIVERSITY Department of Economics

PENN STATE UNIVERSITY Department of Economics PENN STATE UNIVERSITY Department of Economics Econ 597D Sec 001 Computational Economics Gallant Sample Midterm Exam Questions Fall 2015 In class on Oct 20, 2015 1. Write a C++ program and a makefile to

More information

List, Stack, and Queues

List, Stack, and Queues List, Stack, and Queues R. J. Renka Department of Computer Science & Engineering University of North Texas 02/24/2010 3.1 Abstract Data Type An Abstract Data Type (ADT) is a set of objects with a set of

More information

COEN244: Class & function templates

COEN244: Class & function templates COEN244: Class & function templates Aishy Amer Electrical & Computer Engineering Templates Function Templates Class Templates Outline Templates and inheritance Introduction to C++ Standard Template Library

More information

MODULE 33 --THE STL-- ALGORITHM PART I

MODULE 33 --THE STL-- ALGORITHM PART I MODULE 33 --THE STL-- ALGORITHM PART I My Training Period: hours Note: Compiled using Microsoft Visual C++.Net, win32 empty console mode application. g++ compilation examples given at the end of this Module.

More information

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

CSCI-1200 Data Structures Fall 2017 Lecture 10 Vector Iterators & Linked Lists CSCI-1200 Data Structures Fall 2017 Lecture 10 Vector Iterators & Linked Lists Review from Lecture 9 Explored a program to maintain a class enrollment list and an associated waiting list. Unfortunately,

More information

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

CSCI-1200 Data Structures Fall 2017 Lecture 9 Iterators & STL Lists Review from Lecture 8 CSCI-1200 Data Structures Fall 2017 Lecture 9 Iterators & STL Lists Designing our own container classes Dynamically allocated memory in classes Copy constructors, assignment operators,

More information

CMSC 341 Lecture 6 Templates, Stacks & Queues. Based on slides by Shawn Lupoli & Katherine Gibson at UMBC

CMSC 341 Lecture 6 Templates, Stacks & Queues. Based on slides by Shawn Lupoli & Katherine Gibson at UMBC CMSC 341 Lecture 6 Templates, Stacks & Queues Based on slides by Shawn Lupoli & Katherine Gibson at UMBC Today s Topics Data types in C++ Overloading functions Templates How to implement them Possible

More information

Module 9. Templates & STL

Module 9. Templates & STL Module 9 Templates & STL Objectives In this module Learn about templates Construct function templates and class templates STL 2 Introduction Templates: enable you to write generic code for related functions

More information

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

CSCI-1200 Data Structures Spring 2018 Lecture 10 Vector Iterators & Linked Lists CSCI-1200 Data Structures Spring 2018 Lecture 10 Vector Iterators & Linked Lists Review from Lecture 9 Explored a program to maintain a class enrollment list and an associated waiting list. Unfortunately,

More information

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

C++ 프로그래밍실습. Visual Studio Smart Computing Laboratory C++ 프로그래밍실습 Visual Studio 2015 Templates & STL Contents Exercise Practice1 Templates & STL Practice 1-1 Template Classes #include using namespace std; template class Point { private:

More information

CS11 Advanced C++ Spring 2018 Lecture 2

CS11 Advanced C++ Spring 2018 Lecture 2 CS11 Advanced C++ Spring 2018 Lecture 2 Lab 2: Completing the Vector Last week, got the basic functionality of our Vector template working It is still missing some critical functionality Iterators are

More information

Standard Library. Lecture 27. Containers. STL Containers. Standard Library

Standard Library. Lecture 27. Containers. STL Containers. Standard Library Standard Library Lecture 27 Containers (templates) Streams (I/O facilities) Standard Library Portable, type-safe, efficient Try to use as much as possible Heavy use of templates Streams: #include

More information

Vectors. CIS 15 : Spring 2007

Vectors. CIS 15 : Spring 2007 Vectors CIS 15 : Spring 2007 Functionalia Midterm 2 : Ave. 58% (36.9 / 68) Med. 67% (45.5 / 68) Today: Standard Template Library Vector Template Standard Template Library C++ offers extended functionality

More information

Cours de C++ Introduction

Cours de C++ Introduction Cours de C++ Introduction Cécile Braunstein cecile.braunstein@lip6.fr Cours de C++ 1 / 20 Généralité Notes Interros cours 1/3 Contrôle TP 1/3 Mini-projet 1/3 Bonus (Note de Participation) jusqu à 2 points

More information

CSI33 Data Structures

CSI33 Data Structures Outline Department of Mathematics and Computer Science Bronx Community College November 22, 2017 Outline Outline 1 Chapter 12: C++ Templates Outline Chapter 12: C++ Templates 1 Chapter 12: C++ Templates

More information

G52CPP C++ Programming Lecture 18

G52CPP C++ Programming Lecture 18 G52CPP C++ Programming Lecture 18 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Welcome Back 2 Last lecture Operator Overloading Strings and streams 3 Operator overloading - what to know

More information

CS11 Advanced C++ Fall Lecture 1

CS11 Advanced C++ Fall Lecture 1 CS11 Advanced C++ Fall 2006-2007 Lecture 1 Welcome! ~8 lectures Slides are posted on CS11 website http://www.cs.caltech.edu/courses/cs11 ~6 lab assignments More involved labs 2-3 week project at end CS

More information

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

Outline. Variables Automatic type inference. Generic programming. Generic programming. Templates Template compilation Outline EDAF30 Programming in C++ 4. The standard library. Algorithms and containers. Sven Gestegård Robertz Computer Science, LTH 2018 1 Type inference 2 3 The standard library Algorithms Containers Sequences

More information

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

CSCI-1200 Computer Science II Fall 2008 Lecture 15 Associative Containers (Maps), Part 2 CSCI-1200 Computer Science II Fall 2008 Lecture 15 Associative Containers (Maps), Part 2 Review of Lecture 14 Maps are associations between keys and values. Maps have fast insert, access and remove operations:

More information

The Standard Template Library. EECS 211 Winter 2018

The Standard Template Library. EECS 211 Winter 2018 The Standard Template Library EECS 211 Winter 2018 2 Problem: finding the maximum element of a vector A simple fixed-size vector struct: struct Int_vec int* data; size_t size; ; 3 Solution: max_int_vec

More information

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

ECE 462 Exam 1. 6:30-7:30PM, September 22, 2010 ECE 462 Exam 1 6:30-7:30PM, September 22, 2010 I will not receive nor provide aid to any other student for this exam. Signature: You must sign here. Otherwise, the exam is not graded. This exam is printed

More information

Sequential Containers. Ali Malik

Sequential Containers. Ali Malik Sequential Containers Ali Malik malikali@stanford.edu Game Plan Recap Stream wrapup Overview of STL Sequence Containers std::vector std::deque Container Adapters Announcements Recap stringstream Sometimes

More information

Working with Batches of Data

Working with Batches of Data Hartmut Kaiser hkaiser@cct.lsu.edu http://www.cct.lsu.edu/ hkaiser/fall_2012/csc1254.html 2 Abstract So far we looked at simple read a string print a string problems. Now we will look at more complex problems

More information

Exceptions, Templates, and the STL

Exceptions, Templates, and the STL Exceptions, Templates, and the STL CSE100 Principles of Programming with C++, Fall 2018 (based off Chapter 16 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/

More information

Polymorphism. Programming in C++ A problem of reuse. Swapping arguments. Session 4 - Genericity, Containers. Code that works for many types.

Polymorphism. Programming in C++ A problem of reuse. Swapping arguments. Session 4 - Genericity, Containers. Code that works for many types. Session 4 - Genericity, Containers Polymorphism Code that works for many types. Dr Christos Kloukinas City, UoL http://staff.city.ac.uk/c.kloukinas/cpp (slides originally produced by Dr Ross Paterson)

More information

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

Purpose of Review. Review some basic C++ Familiarize us with Weiss s style Introduce specific constructs useful for implementing data structures C++ Review 1 Purpose of Review Review some basic C++ Familiarize us with Weiss s style Introduce specific constructs useful for implementing data structures 2 Class The Class defines the data structure

More information

7 TEMPLATES AND STL. 7.1 Function Templates

7 TEMPLATES AND STL. 7.1 Function Templates 7 templates and STL:: Function Templates 7 TEMPLATES AND STL 7.1 Function Templates Support generic programming functions have parameterized types (can have other parameters as well) functions are instantiated

More information

MODULE 37 --THE STL-- ALGORITHM PART V

MODULE 37 --THE STL-- ALGORITHM PART V MODULE 37 --THE STL-- ALGORITHM PART V My Training Period: hours Note: Compiled using Microsoft Visual C++.Net, win32 empty console mode application. g++ compilation example is given at the end of this

More information

G Programming Languages Spring 2010 Lecture 11. Robert Soulé, New York University

G Programming Languages Spring 2010 Lecture 11. Robert Soulé, New York University G22.2110-001 Programming Languages Spring 2010 Lecture 11 Robert Soulé, New York University 1 Review Last week Constructors, Destructors, and Assignment Operators Classes and Functions: Design and Declaration

More information

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

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures The main body and cout Agenda 1 Fundamental data types Declarations and definitions Control structures References, pass-by-value vs pass-by-references The main body and cout 2 C++ IS AN OO EXTENSION OF

More information

Overview. Part II: Containers and Algorithms. Overview. Overview

Overview. Part II: Containers and Algorithms. Overview. Overview Part II: Containers and Algorithms Overview Sequential Containers Associative Containers Generic Algorithms C++ is about efficient programming with abstractions. The Standard Library is a good example:

More information

C++ Standard Template Library. Contents. Pierre Fierz. 1 Introduction. 2 Organization of STL Header Files. Organization of STL Header Files

C++ Standard Template Library. Contents. Pierre Fierz. 1 Introduction. 2 Organization of STL Header Files. Organization of STL Header Files Contents Chapter 3 1 Lecture Advanced C++ 05.03.2012 2 3 4 Associative 5 Associative 6 Bernese University of Applied Sciences School of Engineering and Information Technology Division of Computer Science

More information

G52CPP C++ Programming Lecture 18. Dr Jason Atkin

G52CPP C++ Programming Lecture 18. Dr Jason Atkin G52CPP C++ Programming Lecture 18 Dr Jason Atkin 1 Last lecture Operator Overloading Strings and streams 2 Operator overloading - what to know Know that you can change the meaning of operators Know that

More information

CSE100. Advanced Data Structures. Lecture 4. (Based on Paul Kube course materials)

CSE100. Advanced Data Structures. Lecture 4. (Based on Paul Kube course materials) CSE100 Advanced Data Structures Lecture 4 (Based on Paul Kube course materials) Lecture 4 Binary search trees Toward a binary search tree implementation using C++ templates Reading: Weiss Ch 4, sections

More information

Vector. Vector Class. class Vector { public: typedef unsigned int size_type;

Vector. Vector Class. class Vector { public: typedef unsigned int size_type; Vector Arrays in C++ must be pre-allocated to accomodate the maximum number of elements. Should an application attempt to add more than this number, the program may abort, or alter storage of adjacent

More information

CMSC 202 Final May 19, Name: UserID: (Circle your section) Section: 101 Tuesday 11: Thursday 11:30

CMSC 202 Final May 19, Name: UserID: (Circle your section) Section: 101 Tuesday 11: Thursday 11:30 CMSC 202 Final May 19, 2005 Name: UserID: (Circle your section) Section: 101 Tuesday 11:30 102 Thursday 11:30 Directions 103 Tuesday 12:30 104 Thursday 12:30 105 Tuesday 1:30 106 Thursday 1:30 This is

More information

ECE 462 Exam 1. 09:30-10:20AM, September 24, 2008

ECE 462 Exam 1. 09:30-10:20AM, September 24, 2008 ECE 462 Exam 1 09:30-10:20AM, September 24, 2008 I certify that I will not receive nor provide aid to any other student for this exam. Signature: You must sign here. Otherwise, the exam is not graded.

More information

Sequential Containers. Ali Malik

Sequential Containers. Ali Malik Sequential Containers Ali Malik malikali@stanford.edu Game Plan Recap Overview of STL Sequence Containers std::vector std::deque Container Adapters Announcements Recap getline vs >> Bug favnum = fullname

More information

Data Structures and Algorithms

Data Structures and Algorithms Data Structures and Algorithms Alice E. Fischer Lecture 3 217 Alice E. Fischer Data Structures L3... 1/31 1 Arrays Growing Arrays vectors 2 3 Empty Lists Inserting Data - Unsorted Inserting Data - Sorted

More information

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

CSCI-1200 Data Structures Spring 2016 Lecture 7 Iterators, STL Lists & Order Notation Today CSCI-1200 Data Structures Spring 2016 Lecture 7 Iterators, STL Lists & Order Notation Another vector operation: pop back Erasing items from vectors is inefficient! Iterators and iterator operations

More information

CSCI-1200 Data Structures Fall 2010 Lecture 8 Iterators

CSCI-1200 Data Structures Fall 2010 Lecture 8 Iterators CSCI-1200 Data Structures Fall 2010 Lecture 8 Iterators Review from Lecture 7 Designing our own container classes Dynamically allocated memory in classes Copy constructors, assignment operators, and destructors

More information

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

Homework 5. Yuji Shimojo CMSC 330. Instructor: Prof. Reginald Y. Haseltine Homework 5 Yuji Shimojo CMSC 330 Instructor: Prof. Reginald Y. Haseltine July 13, 2013 Question 1 Consider the following Java definition of a mutable string class. class MutableString private char[] chars

More information

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

When we program, we have to deal with errors. Our most basic aim is correctness, but we must Chapter 5 Errors When we program, we have to deal with errors. Our most basic aim is correctness, but we must deal with incomplete problem specifications, incomplete programs, and our own errors. When

More information

C++ 11 and the Standard Library: Containers, Iterators, Algorithms

C++ 11 and the Standard Library: Containers, Iterators, Algorithms and the Standard Library:,, Comp Sci 1575 Outline 1 2 3 4 Outline 1 2 3 4 #i n clude i n t main ( ) { i n t v a l u e 0 = 5 ; // C++ 98 i n t v a l u e 1 ( 5 ) ; // C++ 98 i n t v a

More information

Lectures 11,12. Online documentation & links

Lectures 11,12. Online documentation & links Lectures 11,12 1. Quicksort algorithm 2. Mergesort algorithm 3. Big O notation 4. Estimating computational efficiency of binary search, quicksort and mergesort algorithms 5. Basic Data Structures: Arrays

More information

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

Template based set of collection classes STL collection types (container types) STL Collection Types Template based set of collection classes STL collection types (container types) Sequences vector - collection of elements of type T list - doubly linked list, only sequential access

More information

auto map<deque<string>, vector<string>> mymap; for(auto iter = mymap.begin(); iter!= mymap.end(); ++iter) {

auto map<deque<string>, vector<string>> mymap; for(auto iter = mymap.begin(); iter!= mymap.end(); ++iter) { auto auto auto How can we clean this up better? The auto keyword! map mymap; for(auto iter = mymap.begin(); iter!= mymap.end(); ++iter) { } dosomething(*(iter).first, *(iter).second);

More information

6.096 Introduction to C++

6.096 Introduction to C++ MIT OpenCourseWare http://ocw.mit.edu 6.096 Introduction to C++ January (IAP) 2009 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. Massachusetts Institute

More information

PIC 10A. Lecture 23: Intro to STL containers

PIC 10A. Lecture 23: Intro to STL containers PIC 10A Lecture 23: Intro to STL containers STL STL stands for Standard Template Library There are many data structures that share similar features These data structures can be manipulated by a common

More information

CSCI-1200 Data Structures Fall 2014 Lecture 8 Iterators

CSCI-1200 Data Structures Fall 2014 Lecture 8 Iterators Review from Lecture 7 CSCI-1200 Data Structures Fall 2014 Lecture 8 Iterators Designing our own container classes Dynamically allocated memory in classes Copy constructors, assignment operators, and destructors

More information

CSCI 262 Data Structures. Recursive Function Analysis. Analyzing Power. Analyzing Power. Analyzing Power 3/31/2018

CSCI 262 Data Structures. Recursive Function Analysis. Analyzing Power. Analyzing Power. Analyzing Power 3/31/2018 CSCI Data Structures 1 Analysis of Recursive Algorithms, Binary Search, Analysis of RECURSIVE ALGORITHMS Recursive Function Analysis Here s a simple recursive function which raises one number to a (non-negative)

More information

Functions and Methods. Questions:

Functions and Methods. Questions: Functions and Methods Questions: 1 1. What is a reference in C++? 2 2. In the following code, which variable is being declared as a reference? Also, suppose we attempt to change the object of a reference,

More information

2

2 STL Design CSC 330 2 3 4 5 Discussions Associative Containers 6 7 Basic Associative Containers 8 set class 9 map class 10 Example multiset (1) 11 Example multiset (2) 12 Example multiset (3) 13 Example

More information

Lecture 21 Standard Template Library. A simple, but very limited, view of STL is the generality that using template functions provides.

Lecture 21 Standard Template Library. A simple, but very limited, view of STL is the generality that using template functions provides. Lecture 21 Standard Template Library STL: At a C++ standards meeting in 1994, the committee voted to adopt a proposal by Alex Stepanov of Hewlett-Packard Laboratories to include, as part of the standard

More information

Practice test for midterm 2

Practice test for midterm 2 Practice test for midterm 2 April 9, 2 18 1 Functions Write a function which takes in two int parameters and returns their average. (Remember that if a function takes in parameters, it does not need to

More information

CSE 100: C++ TEMPLATES AND ITERATORS

CSE 100: C++ TEMPLATES AND ITERATORS 1 CSE 100: C++ TEMPLATES AND ITERATORS 2 Announcements Look out for the extra weekend section More on git and C++ (iterators) Live demo by your friendly tutors Not mandatory but it will be fun Bring your

More information

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

Lecture 12. Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 1 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

More information

SSE2034: System Software Experiment 3

SSE2034: System Software Experiment 3 SSE2034: System Software Experiment 3 Spring 2016 Jinkyu Jeong (jinkyu@skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu STL Collection Types Template based set of collection

More information

Computer Science II Lecture 2 Strings, Vectors and Recursion

Computer Science II Lecture 2 Strings, Vectors and Recursion 1 Overview of Lecture 2 Computer Science II Lecture 2 Strings, Vectors and Recursion The following topics will be covered quickly strings vectors as smart arrays Basic recursion Mostly, these are assumed

More information

Midterm Review. PIC 10B Spring 2018

Midterm Review. PIC 10B Spring 2018 Midterm Review PIC 10B Spring 2018 Q1 What is size t and when should it be used? A1 size t is an unsigned integer type used for indexing containers and holding the size of a container. It is guarenteed

More information

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

Lecture 8. Xiaoguang Wang. February 13th, 2014 STAT 598W. (STAT 598W) Lecture 8 1 / 47 Lecture 8 Xiaoguang Wang STAT 598W February 13th, 2014 (STAT 598W) Lecture 8 1 / 47 Outline 1 Introduction: C++ 2 Containers 3 Classes (STAT 598W) Lecture 8 2 / 47 Outline 1 Introduction: C++ 2 Containers

More information

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

CSCI-1200 Computer Science II Spring 2006 Test 3 Practice Problem Solutions CSCI-1200 Computer Science II Spring 2006 Test 3 Practice Problem Solutions 1. You are given a map that associates strings with lists of strings. The definition is: map words; Write

More information

(8 1) Container Classes & Class Templates D & D Chapter 18. Instructor - Andrew S. O Fallon CptS 122 (October 8, 2018) Washington State University

(8 1) Container Classes & Class Templates D & D Chapter 18. Instructor - Andrew S. O Fallon CptS 122 (October 8, 2018) Washington State University (8 1) Container Classes & Class Templates D & D Chapter 18 Instructor - Andrew S. O Fallon CptS 122 (October 8, 2018) Washington State University Key Concepts Class and block scope Access and utility functions

More information

Lecture 4a Using The Standard Template Library. Jack Applin, Guest Lecturer

Lecture 4a Using The Standard Template Library. Jack Applin, Guest Lecturer Lecture 4a Using The Standard Template Library Jack Applin, Guest Lecturer November 28 th, 2017 2017-12-04 CS253 Fall 2017 Bruce Draper 1 PA9 is online Announcements Efficiency assignment Same as PA8 But

More information

Sixth lecture; classes, objects, reference operator.

Sixth lecture; classes, objects, reference operator. Sixth lecture; classes, objects, reference operator. 1 Some notes on the administration of the class: From here on out, homework assignments should be a bit shorter, and labs a bit longer. My office hours

More information

Programming in C++ using STL. Rex Jaeschke

Programming in C++ using STL. Rex Jaeschke Programming in C++ using STL Rex Jaeschke Programming in C++ using STL 1997, 1999, 2002, 2007, 2009 Rex Jaeschke. All rights reserved. Edition: 2.0 All rights reserved. No part of this publication may

More information

CSE 100: C++ TEMPLATES AND ITERATORS

CSE 100: C++ TEMPLATES AND ITERATORS CSE 100: C++ TEMPLATES AND ITERATORS Announcements Gradesource and clickers: We ll be making one more pass for unregistered clickers tonight, but after that you ll be on your own How is Assignment 1 going?

More information

Unit 4 Basic Collections

Unit 4 Basic Collections Unit 4 Basic Collections General Concepts Templates Exceptions Iterators Collection (or Container) Classes Vectors (or Arrays) Sets Lists Maps or Tables C++ Standard Template Library (STL Overview A program

More information