Oct 20, 2009 STL Containers Dr. Partha Pratim Das Interra Systems (India) Pvt. Ltd.   Generalizing Data Structures
Agenda STL Components Containers Iterators Algorithms
STL Components Why & How
STL Components STL  is a cooperation of Components Key Components Containers Iterators Algorithms
Containers Manage collection of objects of a kind Every Container Type reflect a conglomeration of requirements May be implemented as  Arrays Linked Lists Special Keys for every Element
Iterators Used to step through elements of collections of objects Collections may be  Containers or Subsets of Containers Offers a small yet common interface for any arbitrary container type This works independent of the Internal Structure Example: Iterator steps to the next element.
Algorithms Used to process elements of collections Examples: Search Sort Modify Use Algorithms use Iterators Algorithms can call user-defined functions (functors)
Concept of STL Separation of Data and Operations Data    Managed by Container Classes Operations    Defined by Configurable Algorithms Iterators    Glue between these Components Contradicts OOP – through separation
Basic Model Algorithms sort, find, search, copy, … Containers   vector, list, map, hash_map, … iterators Separation of concerns Algorithms manipulate data, but don’t know about containers Containers store data, but don’t know about algorithms Algorithms and containers interact through iterators Each container has its own iterator types
Containers Basic Stuff
Types of Containers Sequence Containers Ordered Collection Every element has a certain position Position depends on time and place of Insertion Position is independent of value Predefined Sequence Containers are: vector deque list
Types of Containers Associative Containers Sorted Collection Position of an element depends on its value and a certain sorting criterion Order of Insertion is immaterial Predefined Associative Containers are: set multiset map multimap
Types of Containers Container Adaptors Meets special needs Implemented using fundamental containers Predefined Container Adaptors are: stack queue Priority queue
Common Containers Abilities Constructor Default:  ContType  c Copy:  ContType  c1(c2) Initialize with a Range:  ContType  c(beg, end) Destructor: ~ ContType  c
Common Containers Abilities Size Operations c.size(): Actual number of elements c.empty(): Whether the container is empty c.max_size(): Maximum number of elements possible
Common Containers Abilities Comparison Operators: Operators: ==, !=, <, <=, >, >= Both containers must have the same type Two containers are equal if their elements are equal and have the same order To check if a container is less than another, a lexicographic comparison is done
Common Containers Abilities Assignments and swap() c1 = c2:  Copy all elements of the source container and remove all old elements of the destination container Linear Complexity - expensive c1.swap(c2) / swap(c1, c2) Use when containers have the same type and source is no longer used Swaps some internal pointers that refer to the data (elements, allocator, sorting criterion) Constant Complexity
Common Containers Abilities Iterator Functions c.begin():  Iterator for first element c.end():  Iterator for last element c.rbegin():  Reverse Iterator for first element c.rend():  Reverse Iterator for last element
Common Containers Abilities Manipulators c.insert(pos, elem):  Insert a copy of elem at pos c.erase(beg, end):  Remove all elements in range [beg, end) c.clear():  Remove all elements – makes the container empty
Sequence Container: vector Vector models a dynamic array #include <vector> Special Operations Element Access c.at(idx) / c[idx] c.front() / c.end() Insert / Remove at the back c.push_back(elem) c.pop_back()
Sequence Container: vector Remove the first element with a value std::vector<Elem> coll; std::vector<Elem>::iterator pos; pos = find(coll.begin(), coll.end(), val); if (pos != coll.end()) { coll.erase(pos); }
Sequence Container: deque (“deck”) Similar to Vector Manages elements with Dynamic Array Provides Random Access Almost same interface as Vector Deque is open at both ends. #include <deque> Special Operations Insert / Remove c.push_back(elem) / c.pop_back() c.push_front(elem) / c.pop_front()
Sequence Container: list Manages elements in a doubly linked list #include <list> Element Access front() / back() Insert / Remove push_ / pop_ at both ends Splice / Sort / Merge / Reverse
Sequence Container: strings C++ string classes as containers basic_string<> string wstring
Sequence Container: Ordinary Array Has static or dynamic size Not STL Containers No size() No empty()
Associative Container: set / multiset Sorts the elements according to a sorting criterion Sets do not allow duplicates Multisets allow duplicates #include <set>
Associative Container: map / multimap Manage key/value pairs as elements Sorts the elements according to a sorting criterion that is used for the actual key Maps do not allow duplicates Multimaps allow duplicates #include <map>
Container Adapter: stack #include <stack> Core Operations push() top() pop()
Container Adapter: queue #include <queue> Core Operations push() front() pop() back()
Container Adapter: priority queue priority_queue implements a queue from which elements are read according to their priority #include <queue> Core Operations push() top() pop()
Iterators Basic Stuff
Iterator Interface  Can iterate (navigate) over elements All or part of the elements in an STL container Fundamental Operations operator* operator++ operator== operator!= operator=
Container Interface for Iterators  Fundamental Container Operations for Iterators begin() end()
Basic Iterator Model A pair of iterators define a sequence The beginning (points to the first element – if any) The end (points to the one-beyond-the-last element) … begin: end: An iterator is a type that supports the “iterator operations” ++ Go to next element * Get value == Does this iterator point to the same element as that iterator? Some iterators support more operations (e.g. --, +, and [ ])
Use of Iterators  std::list<char> coll; std::list<char>::const_iterator pos; for(pos = coll.begin(); pos != coll.end(); ++pos) { cout << *pos << ‘ ‘; }
Iterator Categories  Bidirectional Iterators Random Access Iterators
Iterator Adaptors  Insert Iterators Stream Iterators Reverse Iterators
Algorithms Basic Stuff
Algorithm Overview  STL provides several standard algorithms Algorithms are not member functions of containers Algorithms are global functions that operate with iterators Algorithms can operate on various types Algorithms do not belong to Object Oriented Paradigm, they belong to Generic Programming Paradigm #include <algorithm>
References The C++ Standard Library: A Tutorial and Reference Nicolai M. Josuttis Effective STL Scott Meyers C++ Template Metaprogramming Abrahams & Gurtovoy C++ Templates: The Complete Guide   David Vandevoorde & Nicolai M. Josuttis
Thank You

Stl Containers

  • 1.
    Oct 20, 2009STL Containers Dr. Partha Pratim Das Interra Systems (India) Pvt. Ltd. Generalizing Data Structures
  • 2.
    Agenda STL ComponentsContainers Iterators Algorithms
  • 3.
  • 4.
    STL Components STL is a cooperation of Components Key Components Containers Iterators Algorithms
  • 5.
    Containers Manage collectionof objects of a kind Every Container Type reflect a conglomeration of requirements May be implemented as Arrays Linked Lists Special Keys for every Element
  • 6.
    Iterators Used tostep through elements of collections of objects Collections may be Containers or Subsets of Containers Offers a small yet common interface for any arbitrary container type This works independent of the Internal Structure Example: Iterator steps to the next element.
  • 7.
    Algorithms Used toprocess elements of collections Examples: Search Sort Modify Use Algorithms use Iterators Algorithms can call user-defined functions (functors)
  • 8.
    Concept of STLSeparation of Data and Operations Data  Managed by Container Classes Operations  Defined by Configurable Algorithms Iterators  Glue between these Components Contradicts OOP – through separation
  • 9.
    Basic Model Algorithmssort, find, search, copy, … Containers vector, list, map, hash_map, … iterators Separation of concerns Algorithms manipulate data, but don’t know about containers Containers store data, but don’t know about algorithms Algorithms and containers interact through iterators Each container has its own iterator types
  • 10.
  • 11.
    Types of ContainersSequence Containers Ordered Collection Every element has a certain position Position depends on time and place of Insertion Position is independent of value Predefined Sequence Containers are: vector deque list
  • 12.
    Types of ContainersAssociative Containers Sorted Collection Position of an element depends on its value and a certain sorting criterion Order of Insertion is immaterial Predefined Associative Containers are: set multiset map multimap
  • 13.
    Types of ContainersContainer Adaptors Meets special needs Implemented using fundamental containers Predefined Container Adaptors are: stack queue Priority queue
  • 14.
    Common Containers AbilitiesConstructor Default: ContType c Copy: ContType c1(c2) Initialize with a Range: ContType c(beg, end) Destructor: ~ ContType c
  • 15.
    Common Containers AbilitiesSize Operations c.size(): Actual number of elements c.empty(): Whether the container is empty c.max_size(): Maximum number of elements possible
  • 16.
    Common Containers AbilitiesComparison Operators: Operators: ==, !=, <, <=, >, >= Both containers must have the same type Two containers are equal if their elements are equal and have the same order To check if a container is less than another, a lexicographic comparison is done
  • 17.
    Common Containers AbilitiesAssignments and swap() c1 = c2: Copy all elements of the source container and remove all old elements of the destination container Linear Complexity - expensive c1.swap(c2) / swap(c1, c2) Use when containers have the same type and source is no longer used Swaps some internal pointers that refer to the data (elements, allocator, sorting criterion) Constant Complexity
  • 18.
    Common Containers AbilitiesIterator Functions c.begin(): Iterator for first element c.end(): Iterator for last element c.rbegin(): Reverse Iterator for first element c.rend(): Reverse Iterator for last element
  • 19.
    Common Containers AbilitiesManipulators c.insert(pos, elem): Insert a copy of elem at pos c.erase(beg, end): Remove all elements in range [beg, end) c.clear(): Remove all elements – makes the container empty
  • 20.
    Sequence Container: vectorVector models a dynamic array #include <vector> Special Operations Element Access c.at(idx) / c[idx] c.front() / c.end() Insert / Remove at the back c.push_back(elem) c.pop_back()
  • 21.
    Sequence Container: vectorRemove the first element with a value std::vector<Elem> coll; std::vector<Elem>::iterator pos; pos = find(coll.begin(), coll.end(), val); if (pos != coll.end()) { coll.erase(pos); }
  • 22.
    Sequence Container: deque(“deck”) Similar to Vector Manages elements with Dynamic Array Provides Random Access Almost same interface as Vector Deque is open at both ends. #include <deque> Special Operations Insert / Remove c.push_back(elem) / c.pop_back() c.push_front(elem) / c.pop_front()
  • 23.
    Sequence Container: listManages elements in a doubly linked list #include <list> Element Access front() / back() Insert / Remove push_ / pop_ at both ends Splice / Sort / Merge / Reverse
  • 24.
    Sequence Container: stringsC++ string classes as containers basic_string<> string wstring
  • 25.
    Sequence Container: OrdinaryArray Has static or dynamic size Not STL Containers No size() No empty()
  • 26.
    Associative Container: set/ multiset Sorts the elements according to a sorting criterion Sets do not allow duplicates Multisets allow duplicates #include <set>
  • 27.
    Associative Container: map/ multimap Manage key/value pairs as elements Sorts the elements according to a sorting criterion that is used for the actual key Maps do not allow duplicates Multimaps allow duplicates #include <map>
  • 28.
    Container Adapter: stack#include <stack> Core Operations push() top() pop()
  • 29.
    Container Adapter: queue#include <queue> Core Operations push() front() pop() back()
  • 30.
    Container Adapter: priorityqueue priority_queue implements a queue from which elements are read according to their priority #include <queue> Core Operations push() top() pop()
  • 31.
  • 32.
    Iterator Interface Can iterate (navigate) over elements All or part of the elements in an STL container Fundamental Operations operator* operator++ operator== operator!= operator=
  • 33.
    Container Interface forIterators Fundamental Container Operations for Iterators begin() end()
  • 34.
    Basic Iterator ModelA pair of iterators define a sequence The beginning (points to the first element – if any) The end (points to the one-beyond-the-last element) … begin: end: An iterator is a type that supports the “iterator operations” ++ Go to next element * Get value == Does this iterator point to the same element as that iterator? Some iterators support more operations (e.g. --, +, and [ ])
  • 35.
    Use of Iterators std::list<char> coll; std::list<char>::const_iterator pos; for(pos = coll.begin(); pos != coll.end(); ++pos) { cout << *pos << ‘ ‘; }
  • 36.
    Iterator Categories Bidirectional Iterators Random Access Iterators
  • 37.
    Iterator Adaptors Insert Iterators Stream Iterators Reverse Iterators
  • 38.
  • 39.
    Algorithm Overview STL provides several standard algorithms Algorithms are not member functions of containers Algorithms are global functions that operate with iterators Algorithms can operate on various types Algorithms do not belong to Object Oriented Paradigm, they belong to Generic Programming Paradigm #include <algorithm>
  • 40.
    References The C++Standard Library: A Tutorial and Reference Nicolai M. Josuttis Effective STL Scott Meyers C++ Template Metaprogramming Abrahams & Gurtovoy C++ Templates: The Complete Guide David Vandevoorde & Nicolai M. Josuttis
  • 41.