Writing Your Own STL Container Ray Lischner

Slides:



Advertisements
Similar presentations
Data Structures Using C++ 2E
Advertisements

. STL: C++ Standard Library (continued). STL Iterators u Iterators are allow to traverse sequences u Methods  operator*  operator->  operator++, and.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 17: Linked Lists.
More on the STL vector list stack queue priority_queue.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 17 Linked.
C++ Programming: Program Design Including Data Structures, Second Edition Chapter 22: Standard Template Library (STL)
Standard Template Library (STL) Overview – Part 1 Yngvi Bjornsson.
CMSC 202 Lesson 24 Iterators and STL Containers. Warmup Write the class definition for the templated Bag class – A bag has: Random insertion Random removal.
Basic C++ Sequential Container Features
Lecture 11 Standard Template Library Stacks, Queue, and Deque Lists Iterators Sets Maps.
Templates and the STL.
ECE 250 Algorithms and Data Structures Douglas Wilhelm Harder, M.Math. LEL Department of Electrical and Computer Engineering University of Waterloo Waterloo,
Standard Template Library There are 3 key components in the STL –Containers –Iterators –Algorithms Promote reuse More debugged May be more efficient.
Data Structures Using C++ 2E
Containers Overview and Class Vector
CNS  Sequences  vector,deque,list,(string),forward_list  Container Adapters  queue, stack, priority_queue  Associative Containers  set, unordered_set.
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Overview 18.1 Iterators 18.2 Containers 18.3 Generic Algorithms Slide
Generic Programming Using the C++ Standard Template Library.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Standard Template Library (STL)
C++ STL CSCI 3110.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 22: Standard Template Library (STL)
CSE 332: C++ STL containers Review: C++ Standard Template Library (STL) The STL is a collection of related software elements –Containers Data structures:
1. The term STL stands for ? a) Simple Template Library b) Static Template Library c) Single Type Based Library d) Standard Template Library Answer : d.
Friends & Standard Template Library CSCI3110 Advanced Data Structures Lecturer: Dr. Carroll and Nan Chen.
Standard Template Library The Standard Template Library was recently added to standard C++. –The STL contains generic template classes. –The STL permits.
Lists Chapter 8. 2 Linked Lists As an ADT, a list is –finite sequence (possibly empty) of elements Operations commonly include: ConstructionAllocate &
Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 17: Linked Lists.
CS 403, Class 23Slide #1 CS Programming Languages Class 23 November 16, 2000.
 2003 Prentice Hall, Inc. All rights reserved.m ECE 2552 Dr. Këpuska based on Dr. S. Kozaitis Summer Chapter 15 - Class string and String Stream.
Lecture 7 : Intro. to STL (Standard Template Library)
Computer Science and Software Engineering University of Wisconsin - Platteville 11.Standard Template Library Yan Shi CS/SE 2630 Lecture Notes.
A gentle introduction to the standard template library (STL) Some references:
1 STL Containers Copyright Kip Irvine, All rights reserved. Only students enrolled in a class at Florida International University may copy or print.
STL – Standard Template Library L. Grewe. 2 Goals Lots of important algorithms, data structures in CS using Templates. is a software library partially.
The Standard Template Library Container Classes Version 1.0.
Mobility Research Lab mobility.ceng.metu.edu.tr Applied Innovative Interdisciplinary (AI2) Research Lab Short Course on Programming in C/C++
C++ Review STL CONTAINERS.
CSE 332: C++ STL iterators What is an Iterator? An iterator must be able to do 2 main things –Point to the start of a range of elements (in a container)
CS212: Object Oriented Analysis and Design Lecture 26: STL Containers.
CSCI  Sequence Containers – store sequences of values ◦ vector ◦ deque ◦ list  Associative Containers – use “keys” to access data rather than.
Standard Template Library a collection of useful tools.
Unit VI.  C++ templates are a powerful mechanism for code reuse, as they enable the programmer to write code (classes as well as functions) that behaves.
1 The Standard Template Library The STL is a collection of Container classes These are class templates for containers. A container is an object that stores.
Data Structures and Algorithm Analysis Dr. Ken Cosh Linked Lists.
Copyright © 2012 Pearson Education, Inc. Chapter 17: Linked Lists.
Final Exam Review COP4530.
Object-Oriented Programming (OOP) Lecture No. 41
CS212: Object Oriented Analysis and Design
Overview 18.1 Iterators 18.2 Containers 18.3 Generic Algorithms.
Standard Template Library (STL)
What remains Topics Assignments Final exam
Prof. Michael Neary Lecture 7: The STL Prof. Michael Neary
Object Oriented Programming COP3330 / CGS5409
CS212: Object Oriented Analysis and Design
Final Exam Review COP4530.
Generic Programming Karl Lieberherr 12/1/2018 Generic Programming.
Recursive Linked List Operations
Chapter 17: Linked Lists.
Copyright © – Curt Hill STL List Details Copyright © – Curt Hill.
Iterators and STL Containers
C++ STL Stack, Queue, and Deque
Standard Template Library
STL List.
Standard Template Library
Some Definitions vector, string, deque, and list are standard sequence containers. set, multiset, map, multimap, unordered_set, unordered_multiset, unordered_map.
STL List.
Standard Template Library
Presentation transcript:

Writing Your Own STL Container Ray Lischner

Who Am I? Ray Lischner Author ● C++ in a Nutshell ● Learning C++ ● STL Pocket Reference Oregon State University

What Is The STL? A.Silly Three Letters B.Standard Template Library C.So That’s Life D.Sue The Lawyers!

What Is The STL? A.Silly Three Letters B.Standard Template Library C.So That’s Life D.Sue The Lawyers!

What Is The STL? A.Silly Three Letters B.Standard Template Library C.So That’s Life D.Sue The Lawyers!

STL Standard Template Library Containers ● deque, list, map, multimap, multiset, set, vector ● string Iterators Algorithms

STL Standard Template Library Containers ● deque, list, map, multimap, multiset, set, vector ● string ● TR1 adds: array, unordered_map, unordered_multimap, unordered_multiset, unordered_set, Iterators Algorithms

Experience A.I’ve never used STL containers B.I have used containers, iterators, and algorithms a little C.I use containers, iterators, and algorithms often D. I have implemented my own container

What Is a Container? A template, parameterized on element type Stores multiple, homogeneous elements Characterized by complexity metrics ● # of operations for insertion, deletion ● # of operations for lookup

Kinds of Containers Sequence ● deque, list, vector ● array Associative ● map, set ● multimap, multiset ● unordered_map, unordered_set ● unordered_multimap, unordered_multiset

Common Standards Standard dictates common attributes Common sense

Container Review Elements must be assignable, copy- constructible ● T a, b ● T c(a); ● b = a;

Common Members Types: ● value_type, size_type, etc. Constructors: default, copy Destructor Assignment operator Relational and equality operators Member functions ● begin(), end() ● size(), swap(), max_size(), empty()

Sequence Members insert() single or multiple elements erase() single or multiple elements clear() entire container sequence constructors

Integer or Not? Insertion and construction ● insert(position, x, y) ● std::vector example(x, y); If x and y are integers ● Insert or construct x copies of y Else x and y must be iterators ● Copy elements from range [x, y)

Sequence Members Only if constant complexity ● back(), pop_back(), push_back() ● front(), pop_front(), push_front() ● at(), operator[]

Singly-linked List template class slist {... };

Singly-Linked List Review

Inserting a Node

Erasing a Node

Design Decisions Store head only? Store head and tail? Store size or compute as needed?

Front and Back Sequence containers Constant complexity Member functions: ● front(), push_front(), pop_front() ● back(), push_back(), pop_back()

Container Adapters priority_queue, queue, stack queue ● Requires back(), front(), push_back(), pop_front() stack ● Requires back(), push_back(), pop_back()

Heads and Tails Does tail help implement adapters? Call the head “front” or “back”?

Insertion and Erasure Can insert after a given node Can erase the node after a given node Can easily erase at head

Stack vs. Queue Stacks ● head is back Queue ● head is front ● tail is back

What Good Is a Tail? push_back() back_inserter iterator adapter

Container Size Standard does not require constant complexity Gotcha for std::list::size()

Splicing std::list::splice moves nodes from one doubly-linked list to another Splicing is fast But explicit size data member requires linear complexity What’s more important, size or splice?

Lazy Evaluation Explicit size data member Kept up-to-date after insertion, erasure Can be marked as “unknown” after calling splice Call to size() when size is unknown counts every node in list

More Important? A:Optimize size() B:Optimize splice() C:Lazy-evaluation D:I have a better idea

More Important? A:Optimize size() B:Optimize splice() C:Lazy-evaluation D:I have a better idea

Allocators Second template parameter template<class T, class Alloc = ::std::allocator > class slist {... }; Allocates/deallocates memory Constructs/destructs nodes

Separate Allocation and Construction allocate(number_of_items) construct(pointer, value_to_copy) deallocate(pointer, number_of_items) destroy(pointer)

Rebind Alloc allocates items of type T But slist needs to allocate nodes, not elements Need to rebind allocator for nodes ● allocator ::rebind ::other

Avoid Memory Leaks new_node allocates & constructs nodes If constructor throws, new_node should deallocate memory

Iterator Points to one node in a list Advances to next node Compares with other iterators Special value denotes “one past end”

Iterator Review Like a smart pointer slist list; slist ::iterator iter =list.begin(); if (not list.empty()) ++iter; if (iter != list.end()) std::cout << *iter << '\n';

Iterator Review Five flavors ● Input ● Output ● Forward ● Bidirectional ● Random Access

How Are Iterators Used? Insertion point Item(s) to erase Item(s) to copy

Insertion

Erasure

Iterator Design Need to store pointer to prior node Null prior pointer when iterator at head What about end()? Also store pointer to current node Null current pointer means end()

Comparing Iterators Compare iterators by comparing current node pointers Difficulty comparing iterator and const_iterator ● See Scott Meyers’ Effective STL, Item 26 Use a common base class

Iterator Design

Iterator Invalidation Certain operations render iterators invalid Erasure ● Invalidates iterators that point to the erased node ● Or to the subsequent node Insertion ● Invalidates iterators that point to the insertion position

Exception Safety Basic guarantee: list remains valid ● unique Strong guarantee: list is unchanged ● sort No-throw guarantee ● swap, splice

Which Guarantee for insert of one item? A: None B: Basic C: Strong D: No throw

Which Guarantee for insert of one item? A: None B: Basic C: Strong D: No throw

Which Guarantee for insert of multiple items? A: None B: Basic C: Strong D: No throw

Which Guarantee for insert of multiple items? A: None B: Basic C: Strong D: No throw

Rollback insert() multiple items After inserting x items, an exception is thrown Need to erase those x items before returning

Insert or Construct Multiple Items insert() function or constructor: ● insert(position, x, y) ● slist(x, y) If arguments are integers ● Insert x copies of y Else arguments must be iterators ● Copy elements from range [x, y)

Test for Integer Type If TR1 is available, use its type_traits ● #include ● Specialize on compile-time constant std::tr1::is_integral ::value Use Boost ● #include ● Specialize on boost::is_integral ::value Write your own

Miscellaneous List Functions splice merge, merge_sort unique Relational and equality operators

For More Information C++ in a Nutshell, Ray Lischner The C++ Standard Library, Nicolai Josuttis Effective STL, Scott Meyers The C++ Standard Template Library, Plauger, et al. STL Pocket Reference, Ray Lischner

Questions?

Thank You Ray Lischner