introduction to the
play

Introduction to the Provides the ability to use: C++ Standard - PDF document

2/9/2017 The C++ Standard Library Introduction to the Provides the ability to use: C++ Standard Library. String Types Data Structures (linked list, dynamic arrays, priority queues, binary trees etc) For : COP 3330. Algorithms


  1. 2/9/2017 The C++ Standard Library Introduction to the  Provides the ability to use: C++ Standard Library.  String Types  Data Structures (linked list, dynamic arrays, priority queues, binary trees etc) For : COP 3330.  Algorithms (Sorting and Searching…) Object oriented Programming (Using C++)  IO ht t p: / / www. com pgeom . com / ~pi yush/ t each/ 3330  Classes for internationalization support. Piyush Kumar The C++ Standard Library C++ Standard Library  Not very homogeneous:  Containers  Objects that hold/contain other objects.  String classes are safe and convenient to  Examples: vector, string use (almost self explanatory).  Algorithms  The Standard Template Library (STL)  Work on the containers optimizes for performance and is not required to check for errors. To use it well,  Examples: sort, search you need to understand the concepts and  Iterators apply them carefully.  Provide pointer like interface to containers. Other components Containers  Allocators : Provide memory  Of course: Contain objects/built in management for containers. Can be types. customized.  More powerful than arrays.  Adaptors : A mechanism to make one  Grow (and shrink?) dynamically thing act like another. Example: Stack.  Manage their own memory  Function objects : A function object or a functor , is a construct allowing an  Keep track of their size object to be invoked or called as if it  Allow optimal algorithmic operations were an ordinary function. like scan, sorts etc. 1

  2. 2/9/2017 Containers Containers  Standard STL sequence Containers:  Prefer sequential containers to arrays.  vector, string, deque and list  Use vector by default • bitset, queue  Use list when there are a lot of • valarray, priority_queue insertions/deletions in the middle of the sequence.  Use deque when there is a lot of insertion at the beginning or the end of the sequence. What is a vector? Vector Interface allocator template <class T, class Allocator = allocator<T> > data class vector { size public: ... explicit vector(const Allocator& = Allocator()); capacity explicit vector(size_type n, const T& value = T(), const Allocator& = Allocator()); ... void reserve(size_type n); ... A contiguous array of elements data  void resize(size_type sz, const T& c = T()); The first “size” elements are constructed (initialized)  ... size The last “capacity - size” elements are uninitialized void push_back(const T& x);  void pop_back(); Four data members  capacity ...  data pointer iterator insert(iterator position, const T& x);  size allocator void insert(iterator position, size_type n, const T& x); or equivalent  capacity ... iterator erase(iterator position);  allocator iterator erase(iterator first, iterator last); ... Sample data layout: Internals. void clear(); }; Vectors Containers : is empty? #include <vector>  template <class T, class Allocator =  Always use: allocator<T> > class vector { …}  if(icontainer.empty()) …  A default allocator is provided.  Instead of if(icontainer.size() == 0)  T is the type of the object stored in the  For some containers, calculating size vector. takes linear time.  Constructors for vector:  vector<int> ivec1;  vector<int> ivec2(3,9);  vector<int> ivec3(ivec2); 2

  3. 2/9/2017 An example usage An example usage #include <vector> #include <vector> #include <iostream> #include <iostream> pk@linprog4:~>./a.out vec[0]=3 using namespace std; using namespace std; vec[1]=6 vec[2]=7 int main() { int main() { vec[3]=5 pk@linprog4:~>./a.out vector<int> vec(10); // Creates a vector Segmentation fault (core dumped) vec[4]=3 vector<int> ivec; vec[5]=5 cout << ivec[0]; //error // Initializes the vector vec[6]=6 vector<int> ivec2(10); for(int i=0; i < vec.size(); i++) { vec[7]=2 // subscripts available: 0..9 vec[i] = rand() % 10; vec[8]=9 cout << ivec[10]; // error cout << " vec[" << i << "]=" vec[9]=1 Make this your friend… << vec[i] << endl; return 0; }; } return 0; } Iterators Iterators  Browsers for containers.  A replacement for subscripting, for example in case of vectors: v[i]  Allows restricted access to objects stored in a container.  Subscripts are not available for all containers but iterators are.  Can be a class, data structure or an Abstract Data Type.  You can think of an iterator as pointing to an item that is part of a larger container of items. Iterators Iterators  Support the following operations:  Container.begin() : All containers  Operator * : Element at the current position (example: (*it)). You can use “->” to access support a function called begin, which object members directly from the iterator. will return an iterator pointing to the (Like a pointer) beginning of the container (the first  Operator++ : Moves the iterator to the next element) element. Most iterators will also allow you to  Container.end() : returns an iterator use “ - - ” for stepping back one element. corresponding to having reached the end  Operator == and != : Compare two iterators of the container. (Not the last element) for whether they represent the same position (not the same element).  Operator = : Assigns an iterator. 3

  4. 2/9/2017 Iterators Iterators  Vector iterator picture.  Defining an iterator: std:: class_name < template_parameters >::iterator name; v.end() v.begin()  Example: std::vector<int>::iterator vit = myvec.begin(); cout << (*vit) << endl; data  Printing all elements of a container.  Reason for half-open range: std::container_type<template_parameter>::iterator pos; for ( pos = container.begin();  Easy looping pos != container.end(); ++pos)  Empty containers  begin() == end() cout << (*pos) << endl; Iterators : Examples Iterators: Examples #include <vector> #include <iostream> The non-STL way, using subscripts to access data: int main() { using namespace std; using namespace std; vector<int> myIntVector; // vector<int>::iterator myIntVectorIterator; (use auto instead) vector<int> myIntVector; // Add some elements to myIntVector // Add some elements to myIntVector myIntVector.push_back(1); myIntVector.push_back(1); //adds an element to end of vector. myIntVector.push_back(4); myIntVector.push_back(4); myIntVector.push_back(8); myIntVector.push_back(8); for (auto myIntVectorIterator = myIntVector.begin(); for(int y=0; y<myIntVector.size(); y++) { myIntVectorIterator != myIntVector.end(); cout<<myIntVector[y]<<" "; //Should output 1 4 8 myIntVectorIterator++) { } cout << *myIntVectorIterator << " "; // Should output 1 4 8 } } Iterator Types Iterators  Input Iterator : read only, forward moves. Type of iterator Example  Output Iterator : write only, forward moves. Input Iterator istream_iterator  Forward Iterator: Both read/write with (++) support Output Iterator ostream_iterator, inserter,  Backward: Both read/write with (--) support front_inserter, back inserter  Bi-Directional :Read write and Both ++ or – Bi-directional iterator list, set, multiset, map, support. multimap Most Common  Random: Read/Write/Random access. Random access iterator Vector, deque (Almost act like pointers) 4

  5. 2/9/2017 Random Access Iterators Back to vectors  Iterator type: Random-access  Allow arithmetic  Operator [] overloaded  it+n v.size() Number of elements in vector  The result will be the element corresponding v.clear() Removes all elements to the nth item after the item pointed to be the current iterator. v.pop_back() Removes last element  it – n also allowed v.push_back(elem) Adds elem at end of vector  (it1 – it2) allowed v.insert(pos,elem) Inserts elem at position pos and • Example: Type of this operation for vectors is returns the position of the new defined by vector<T>::difference_type. element. v.erase(pos) Removes the element at the iterator position pos and returns Another form: the position of the next element. v.erase(bpos,epos) Back to vectors Important facts v.max_size() Maximum number of elements possible (in entire memory!).  For vectors, the C++ standard states: v.capacity() Returns maximum number of  &v[i] = &v[0] + i elements without reallocation v.reserve(new_size) Increases capacity to new_size. vector < char > vv; vv.push_back ( 'P' ); vv.push_back ( 'Q' ); v.at(idx) Returns the element with index vv.push_back ( 'R' ); idx. Throws range error vv.push_back ( '\0' ); exception if idx is out of range. printf("%s\n",&vv[0]); v.front() , v.back() Returns first , last element. Output : PQR v.resize(new_size) Changes the size to new_size. The swap trick. Important Facts  To trim capacity, you can use the  When deleting containers of following trick: newed/malloced elements, remember to delete/free them before deleting the  std::vector<T>(v).swap(v); container.  Makes capacity = size.  Thread safety of STL containers: • Example: vector<int>(ivec2).swap(ivec2);  Multiple readers are ok  Multiple writers to different containers are ok. 5

Recommend


More recommend