1 / 31

Overview of the STL & Assorted C++ features

Junaed Sattar November 19, 2008 Lecture 12. Overview of the STL & Assorted C++ features. The STL. Stands for Standard Template Library set of C++ template classes to provide common programming data structures and functions officially (from SGI's STL site):

Télécharger la présentation

Overview of the STL & Assorted C++ features

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Junaed Sattar November 19, 2008 Lecture 12 Overview of the STL &Assorted C++ features

  2. The STL • Stands for Standard Template Library • set of C++ template classes to provide common programming data structures and functions • officially (from SGI's STL site): • library of container classes, algorithms, and iterators • provides many of the basic algorithms and data structures of computer science

  3. Basic Characteristics of the STL • a generic library, meaning that its components are heavily parameterized: • almost every component in the STL is a template. • make sure that you understand how templates work in C++ before you use the STL!

  4. Categories • Categorized in the following groupings • Containers and algorithms • classes for containing (holding) other objects and related algorithms for data manipulations • Iterators • generalization of pointers, which applies to any object stored in container classes • Concepts, Modeling, Refinement • rules about the set of types that may correctly be substituted for the formal template parameters • Utilities • Miscellaneous utilities

  5. Containers/Algorithms • Includes classes vector, list, deque, set, multiset, map, multimap, hash_set, hash_multiset, hash_map, and hash_multimap • Each of these classes is a template, and can be instantiated to contain any type of object • Generic algorithms manipulate data stored in these container objects

  6. Container: Vector • Avoids managing dynamic memory by hand vector<string> SS;SS.push_back("The number is 10");SS.push_back("The number is 20");SS.push_back("The number is 30");// Loop by indexfor( int ii=0; ii < SS.size(); ii++ ) { cout << SS[ii] << endl; }

  7. Algorithm Example • // Reverse the elements in the Vector • reverse(v.begin(), v.end()); • // Loop by index • for( int ii=0; ii < SS.size(); ii++ ) { • cout << SS[ii] << endl; • } • Outputs: • The number is 30 • The number is 20 • The number is 10

  8. Iterators • STL class to represent position in an STL container • i.e. objects that point to other objects • An iterator is declared to be associated with a single container class type • i.e. to access a vector of strings, we require an iterator to vector<string>

  9. Types • input_iterator: Read values with forward movement. • output_iterator: Write values with forward movement. • forward_iterator : Read or write values with forward movement. These combine the functionality of input and output iterators with the ability to store the iterators value. • bidirectional_iterator: Read and write values with forward and backward movement. • random_iterator: Read and write values with random access. These are the most powerful iterators, combining the functionality of bidirectional iterators with the ability to do pointer arithmetic and pointer comparisons. • reverse_iterator: Either a random iterator or a bidirectional iterator that moves in reverse direction.

  10. Iterators: Vector • vector<string> SS;SS.push_back("The number is 10");SS.push_back("The number is 20");SS.push_back("The number is 30");vector<string>::iterator cii; • for(cii=SS.begin(); cii!=SS.end(); cii++){ cout << *cii << endl;}

  11. Another example • #include <iostream.h>#include <vector.h>#include <algo.h>#include <iterator.h> • int main (int argc, char *argv[]){ int n = atoi (argv[1]); vector<int> v;for( int i = 0; i < n; i++ ) v.push_back (i); • random_shuffle (v.begin(), v.end()); • // print • copy( v.begin(), v.end(), ostream_iterator<int>( cout, "\n")); • }

  12. Sort: STL Style • void sort( iterator start, iterator end ); • void sort( iterator start, iterator end, StrictWeakOrdering cmp ); • sorts the elements in the range [start,end) into ascending order • if strict weak ordering function object cmp is given, then it will be used to compare two objects instead of the < operator.

  13. Example sort • vector<int> v; • sort( v.begin(), v.end() ); • And also, • int array[] = { 23, -1, 9999, 0, 4 }; • unsigned int array_size = 5; • sort( array, array+array_size );

  14. Compare function • bool cmp( int a, int b ) { return a > b;} • sort( v.begin(), v.end(), cmp );

  15. Auto pointers • Pointers, but do not require explicit deallocation • i.e. does not have to be “delete”-ed • but only individual pointers, not arrays • again, this is a templated type • similar to garbage collection in Java

  16. Auto Pointer Example • #include <iostream>#include <memory>using namespace std;class X { public: X() { cout << "constructing\n"; } ~X() { cout << "destructing\n"; } void f() { cout << "Inside f()\n"; }}; • int main() {auto_ptr<X> p1(new X), p2;p2 = p1; // transfer ownershipp2->f();X *ptr = p2.get(); // can assign to a normal pointerptr->f();return 0;}

  17. More STL Reference • The STL Book (it's in the course outline) • STL Homepage: http://www.sgi.com/tech/stl/ • Another tutorial on the STL • http://www.cs.brown.edu/people/jak/proglang/cpp/stltut/

  18. Namespaces • allows grouping of entities (classes, functions, variables etc) under one name • similar to a Java package • helps to create sub-scopes for identifiers • To declare a namespace: namespace namespace_identifier {// declare entities here}

  19. Example usage namespace Probability { double pdf, cdf; double *distribution; class GaussianDistribution { ... }; } int main() { using Probability::GaussianDistribution; GaussianDistribution GD; ... }

  20. The using keyword • used to introduce a name from a namespace into the current declarative region • i.e. using Probability::pdf • also can be used to introduce entire namespaces • using namespace Probability

  21. utility of namespaces • functionality of namespaces is especially useful to avoid redefinition errors • also known as naming collision • in the case that a global object or function uses the same identifier as another one • commonplace in large projects, multiple programmers working on the same program

  22. “Collision avoidance” namespace Cars { double velocity = 10; }; namespace Planes { double velocity = 1000; } int main(){ cout << Cars::velocity << “\n”; cout << Planes::velocity << “\n”; }

  23. Namespace using scope • using, using namespaceare valid in the declaring code block, or global scope if declared at the beginning of the program • remember, curly braces create code blocks In C++

  24. C++ Exceptions • react to unexpected circumstances in code • using exception handlers • place suspect code under inspection • using a try block • control goes to exception handlers in case of exception • all the catch blocks

  25. Syntax • try{ // place your code here, for example: ch = new char[100]; throw 100;}catch( std::bad_alloc ex ){ cout << ex.what();}catch( int exi ) { cout << exi; }catch(...){ // catches everything else, default hander}

  26. Exception Throwing • thrown exception can be of any type • basic types (int, char, float... ) • any object derived from the standard class called exception • exception is declared in the header <exceptions> • virtual member function what returns a null-terminated character sequence (char *) • override in derived classes to contain some sort of description of the exception

  27. User-defined exceptions • functions throwing exceptions: • void GetRoots() throw (int) • throws an integer exception (catch int) • void GetRoots() • can throw any type of exception • void GetRoots throw () • cannot throw any type of exception

  28. Custom Exception Class class CustomException: public exception { virtual const char* what() const throw() { return "Custom exception happened"; } }; int main() { try { CustomExcpetion custEx; throw custEx; } catch( exception& e ){ // reference to base is ok cout << e.what() << endl; } return 0; }

  29. Standard Library Exceptions

  30. Miscellaneous • C++ structs: • Same as classes, except by default, everything is public (classes have everything private by default) • C structs do not have methods. Only data. • C has no concept of data-function binding • struct Complex { private: double real, imaginary; public: Complex(); ...}

  31. return(EXIT_SUCCESS)? • Concluding remarks.

More Related