C++ Standard Template Library, Study notes of C programming

L14: C++ STL. STL Containers ☹. ❖ STL containers store by value, not by reference. ▫ When you insert an object, the container makes a copy.

Typology: Study notes

2021/2022

Uploaded on 08/05/2022

jacqueline_nel
jacqueline_nel 🇧🇪

4.4

(242)

3.2K documents

1 / 22

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
CSE333, Summer 2018L14: C++ STL
C++ Standard Template Library
CSE 333 Summer 2018
Instructor: Hal Perkins
Teaching Assistants:
Renshu Gu William Kim Soumya Vasisht
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16

Partial preview of the text

Download C++ Standard Template Library and more Study notes C programming in PDF only on Docsity!

C++ Standard Template Library

CSE 333 Summer 2018

Instructor: Hal Perkins

Teaching Assistants:

Renshu Gu William Kim Soumya Vasisht

C++’s Standard Library v C++’s Standard Library consists of four major pieces:

  1. The entire C standard library
  2. C++’s input/output stream library
  • std::cin, std::cout, stringstreams, fstreams, etc.
  1. C++’s standard template library ( STL ) ☜
  • Containers, iterators, algorithms (sort, find, etc.), numerics
  1. C+’+’s miscellaneous library
  • Strings, exceptions, memory allocation, localization

STL Containers L v STL containers store by value , not by reference § When you insert an object, the container makes a copy § If the container needs to rearrange objects, it makes copies

  • e.g. if you sort a vector, it will make many, many copies
  • e.g. if you insert into a map, that may trigger several copies § What if you don’t want this (disabled copy constructor or copying is expensive)?
  • You can insert a wrapper object with a pointer to the object
  • We’ll learn about these “smart pointers” soon

Our Tracer Class v Wrapper class for an unsigned int value_ § Default ctor, cctor, dtor, op=, op< defined § friend function operator<< defined § Also holds unique unsigned int id_ (increasing from 0 ) § Private helper method PrintID () to return "(id_,value_)" as a string § Class and member definitions can be found in Tracer.h and Tracer.cc v Useful for tracing behaviors of containers § All methods print identifying messages § Unique id_ allows you to follow individual instances

vector/Tracer Example

vectorfun.cc

#include #include #include "Tracer.h" using namespace std; int main (int argc, char** argv) { Tracer a, b, c; vector vec; cout << "vec.push_back " << a << endl; vec. push_back (a); cout << "vec.push_back " << b << endl; vec. push_back (b); cout << "vec.push_back " << c << endl; vec. push_back (c); cout << "vec[0]" << endl << vec[0] << endl; cout << "vec[2]" << endl << vec[ 2 ] << endl; return 0 ; }

STL iterator v Each container class has an associated iterator class ( e.g. vector::iterator) used to iterate through elements of the container § http://www.cplusplus.com/reference/std/iterator/ § Iterator range is from begin up to end

  • end is one past the last container element! § Some container iterators support more operations than others
  • All can be incremented (++), copied, copy-constructed
  • Some can be dereferenced on RHS ( e.g. x = *it;)
  • Some can be dereferenced on LHS ( e.g. *it = x;)
  • Some can be decremented (--)
  • Some support random access ([], +, - , +=, - =, <, > operators)

Type Inference (C++11) v The auto keyword can be used to infer types § Simplifies your life if, for example, functions return complicated types § The expression using auto must contain explicit initialization for it to work // Calculate and return a vector // containing all factors of n std::vector Factors (int n); void foo (void) { // Manually identified type std::vector facts1 = Factors ( 324234 ); // Inferred type auto facts2 = Factors ( 12321 ); // Compiler error here auto facts3; }

auto and Iterators v Life becomes much simpler! for (vector::iterator it = vec. begin (); it < vec. end (); it++) { cout << *it << endl; } for (auto it = vec. begin (); it < vec. end (); it++) { cout << *it << endl; }

Updated iterator Example #include #include "Tracer.h" using namespace std; int main (int argc, char** argv) { Tracer a, b, c; vector vec; vec. push_back (a); vec. push_back (b); vec. push_back (c); cout << "Iterating:" << endl; // "auto" is a C++11 feature not available on older compilers for (auto& p : vec) { cout << p << endl; } cout << "Done iterating!" << endl; return 0 ; }

vectoriterator_2011.cc

STL Algorithms v A set of functions to be used on ranges of elements § Range: any sequence that can be accessed through iterators or pointers , like arrays or some of the containers § General form: v Algorithms operate directly on range elements rather than the containers they live in § Make use of elements’ copy ctor, =, ==, !=, < § Some do not modify elements

  • e.g. find, count, for_each, min_element, binary_search § Some do modify elements
  • e.g. sort, transform, copy, swap algorithm ( begin , end , ...);

STL list v A generic doubly-linked list § http://www.cplusplus.com/reference/stl/list/ § Elements are not stored in contiguous memory locations

  • Does not support random access ( e.g. cannot do list[5]) § Some operations are much more efficient than vectors
  • Constant time insertion, deletion anywhere in list
  • Can iterate forward or backwards § Has a built-in sort member function
  • Doesn’t copy! Manipulates list structure instead of element values

list Example #include #include #include "Tracer.h" using namespace std; void PrintOut (const Tracer& p) { cout << " printout: " << p << endl; } int main (int argc, char** argv) { Tracer a, b, c; list lst; lst. push_back (c); lst. push_back (a); lst. push_back (b); cout << "sort:" << endl; lst. sort (); cout << "done sort!" << endl; for_each (lst. begin (), lst. end (), & PrintOut ); return 0 ; }

listexample.cc

map Example void PrintOut (const pair<Tracer,Tracer>& p) { cout << "printout: [" << p.first << "," << p.second << "]" << endl; } int main (int argc, char** argv) { Tracer a, b, c, d, e, f; map<Tracer,Tracer> table; map<Tracer,Tracer>::iterator it; table. insert (pair<Tracer,Tracer>(a, b)); table[c] = d; table[e] = f; cout << "table[e]:" << table[e] << endl; it = table. find (c); cout << "PrintOut(it), where it = table.find(c)" << endl; PrintOut (it); cout << "iterating:" << endl; for_each (table. begin (), table. end (), & PrintOut ); return 0 ; }

mapexample.cc

Unordered Containers (C++11) v unordered_map, unordered_set § And related classes unordered_multimap, unordered_multiset § Average case for key access is O(1)

  • But range iterators can be less efficient than ordered map/set § See C++ Primer , online references for details