Presentation is loading. Please wait.

Presentation is loading. Please wait.

Writing Your Own STL Container Ray Lischner

Similar presentations


Presentation on theme: "Writing Your Own STL Container Ray Lischner"— Presentation transcript:

1 Writing Your Own STL Container Ray Lischner lisch@cpphelp.com

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

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

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

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

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

7 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

8 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

9 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

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

11 Common Standards Standard dictates common attributes Common sense

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

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

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

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

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

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

18 Singly-Linked List Review

19 Inserting a Node

20 Erasing a Node

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

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

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

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

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

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

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

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

29 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?

30 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

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

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

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

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

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

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

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

38 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';

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

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

41 Insertion

42 Erasure

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

44 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

45 Iterator Design

46 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

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

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

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

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

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

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

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

54 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

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

56 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

57 Questions?

58 Thank You Ray Lischner lisch@cpphelp.com


Download ppt "Writing Your Own STL Container Ray Lischner"

Similar presentations


Ads by Google