writing your own stl container

58
Writing Your Own STL Container Ray Lischner [email protected]

Upload: dawn-mack

Post on 30-Dec-2015

21 views

Category:

Documents


0 download

DESCRIPTION

Ray Lischner [email protected]. Writing Your Own STL Container. 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!. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Writing Your Own STL Container

Writing Your Own STL Container

Ray Lischner

[email protected]

Page 2: Writing Your Own STL Container

Who Am I?

• Ray Lischner

• Author● C++ in a Nutshell● Learning C++● STL Pocket Reference

• Oregon State University

Page 3: Writing Your Own STL Container

What Is The STL?

• A. Silly Three Letters

• B. Standard Template Library

• C. So That’s Life

• D. Sue The Lawyers!

Page 4: Writing Your Own STL Container

What Is The STL?

• A. Silly Three Letters

• B. Standard Template Library

• C. So That’s Life

• D. Sue The Lawyers!

Page 5: Writing Your Own STL Container

What Is The STL?

• A. Silly Three Letters

• B. Standard Template Library

• C. So That’s Life

• D. Sue The Lawyers!

Page 6: Writing Your Own STL Container

STL

• Standard Template Library

• Containers● deque, list, map, multimap, multiset, set, vector● string

• Iterators

• Algorithms

Page 7: Writing Your Own STL Container

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

Page 8: Writing Your Own STL Container

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

Page 9: Writing Your Own STL 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

Page 10: Writing Your Own STL Container

Kinds of Containers

• Sequence● deque, list, vector● array

• Associative● map, set● multimap, multiset● unordered_map, unordered_set● unordered_multimap, unordered_multiset

Page 11: Writing Your Own STL Container

Common Standards

• Standard dictates common attributes

• Common sense

Page 12: Writing Your Own STL Container

Container Review

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

Page 13: Writing Your Own STL Container

•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()

Page 14: Writing Your Own STL Container

Sequence Members

• insert() single or multiple elements

• erase() single or multiple elements

• clear() entire container

• sequence constructors

Page 15: Writing Your Own STL Container

Integer or Not?

• Insertion and construction● insert(position, x, y)● std::vector<sometype> 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)

Page 16: Writing Your Own STL Container

Sequence Members

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

Page 17: Writing Your Own STL Container

Singly-linked List

template<class T>

class slist {

...

};

Page 18: Writing Your Own STL Container

Singly-Linked List Review

next

value next

value

next

value

next

value

Page 19: Writing Your Own STL Container

Inserting a Node

next

value next

value

next

value

next

value

next

value

Page 20: Writing Your Own STL Container

Erasing a Node

next

value next

value

next

value

next

value

next

value

Page 21: Writing Your Own STL Container

Design Decisions

• Store head only?

• Store head and tail?

• Store size or compute as needed?

Page 22: Writing Your Own STL Container

Front and Back

• Sequence containers

• Constant complexity

• Member functions:● front(), push_front(), pop_front()● back(), push_back(), pop_back()

Page 23: Writing Your Own STL Container

Container Adapters

• priority_queue, queue, stack

• queue● Requires back(), front(), push_back(),

pop_front()

• stack● Requires back(), push_back(), pop_back()

Page 24: Writing Your Own STL Container

Heads and Tails

• Does tail help implement adapters?

• Call the head “front” or “back”?

Page 25: Writing Your Own STL Container

Insertion and Erasure

• Can insert after a given node

• Can erase the node after a given node

• Can easily erase at head

Page 26: Writing Your Own STL Container

Stack vs. Queue

• Stacks● head is back

• Queue● head is front● tail is back

Page 27: Writing Your Own STL Container

What Good Is a Tail?

• push_back()

• back_inserter iterator adapter

Page 28: Writing Your Own STL Container

Container Size

• Standard does not require constant complexity

• Gotcha for std::list::size()

Page 29: Writing Your Own STL Container

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?

Page 30: Writing Your Own STL Container

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

Page 31: Writing Your Own STL Container

More Important?

• A: Optimize size()

• B: Optimize splice()

• C: Lazy-evaluation

• D: I have a better idea

Page 32: Writing Your Own STL Container

More Important?

• A: Optimize size()

• B: Optimize splice()

• C: Lazy-evaluation

• D: I have a better idea

Page 33: Writing Your Own STL Container

•Allocators

• Second template parametertemplate<class T,

class Alloc = ::std::allocator<T> >

class slist { ... };

• Allocates/deallocates memory

• Constructs/destructs nodes

Page 34: Writing Your Own STL Container

Separate Allocation and Construction

• allocate(number_of_items)

• construct(pointer, value_to_copy)

• deallocate(pointer, number_of_items)

• destroy(pointer)

Page 35: Writing Your Own STL Container

Rebind

• Alloc<T> allocates items of type T

• But slist needs to allocate nodes, not elements

• Need to rebind allocator for nodes● allocator<T>::rebind<node_type>::other

Page 36: Writing Your Own STL Container

Avoid Memory Leaks

• new_node allocates & constructs nodes

• If constructor throws, new_node should deallocate memory

Page 37: Writing Your Own STL Container

Iterator

• Points to one node in a list

• Advances to next node

• Compares with other iterators

• Special value denotes “one past end”

Page 38: Writing Your Own STL Container

Iterator Review

• Like a smart pointerslist<int> list;

slist<int>::iterator iter =list.begin();

if (not list.empty())

++iter;

if (iter != list.end())

std::cout << *iter << '\n';

Page 39: Writing Your Own STL Container

Iterator Review

• Five flavors● Input● Output● Forward● Bidirectional● Random Access

Page 40: Writing Your Own STL Container

How Are Iterators Used?

• Insertion point

• Item(s) to erase

• Item(s) to copy

Page 41: Writing Your Own STL Container

Insertion

next

value next

value

next

value

next

value

next

valueiterator

Page 42: Writing Your Own STL Container

Erasure

next

value next

value

next

value

next

value

next

valueiterator

Page 43: Writing Your Own STL Container

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()

Page 44: Writing Your Own STL Container

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

Page 45: Writing Your Own STL Container

Iterator Design

iterator_base

operator==operator!=

iterator const_iterator

Page 46: Writing Your Own STL Container

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

Page 47: Writing Your Own STL Container

Exception Safety

• Basic guarantee: list remains valid● unique

• Strong guarantee: list is unchanged● sort

• No-throw guarantee● swap, splice

Page 48: Writing Your Own STL Container

Which Guarantee for insert of one item?

• A: None

• B: Basic

• C: Strong

• D: No throw

Page 49: Writing Your Own STL Container

Which Guarantee for insert of one item?

• A: None

• B: Basic

• C: Strong

• D: No throw

Page 50: Writing Your Own STL Container

Which Guarantee for insert of multiple items?

• A: None

• B: Basic

• C: Strong

• D: No throw

Page 51: Writing Your Own STL Container

Which Guarantee for insert of multiple items?

• A: None

• B: Basic

• C: Strong

• D: No throw

Page 52: Writing Your Own STL Container

Rollback

• insert() multiple items

• After inserting x items, an exception is thrown

• Need to erase those x items before returning

Page 53: Writing Your Own STL Container

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)

Page 54: Writing Your Own STL Container

Test for Integer Type

• If TR1 is available, use its type_traits● #include <type_traits>● Specialize on compile-time constant

std::tr1::is_integral<T>::value

• Use Boost● #include <boost/type_traits.hpp>● Specialize on boost::is_integral<T>::value

• Write your own

Page 55: Writing Your Own STL Container

Miscellaneous List Functions

• splice

• merge, merge_sort

• unique

• Relational and equality operators

Page 56: Writing Your Own STL Container

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

Page 57: Writing Your Own STL Container

Questions?

Page 58: Writing Your Own STL Container

Thank You

Ray Lischner

[email protected]