1 / 38

Container Classes General Vectors Lists Maps ADT Review Classes - Declaration

Lecture 1 – Introduction: C++, Data Structures. Container Classes General Vectors Lists Maps ADT Review Classes - Declaration -Private/Public Sections Example time24 function addTime (). Scope Resolution Operator Rectangle Class Example APIs and Example - Constructor

Download Presentation

Container Classes General Vectors Lists Maps ADT Review Classes - Declaration

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. Lecture 1 – Introduction: C++, Data Structures • Container Classes • General • Vectors • Lists • Maps • ADT Review • Classes • -Declaration • -Private/Public Sections • Example • time24 function addTime () • Scope Resolution Operator • Rectangle Class Example • APIs and Example • -Constructor • -Operations • -RandomNumber Class • Generating Random Numbers • String Functions and Operations

  2. Data Structures/Algorithms • Programs = Data Structures + Algorithms (Wirth) • Importance – write program w/o either • Data Structures – (efficient) storage and manipulation of data sets • Arrays, strings, lists, stacks, trees • Algorithms • Find, insert, erase, sort • “Efficient”? • Quantify (Lord Kelvin) • Space • Speed • Want machine independent metrics – Big-O notation

  3. Algorithm Complexity • Big-O notation – machine-independent means for determining efficiency of algorithm • Idea: relate # of key operations or stmts to input size • op count == 9N2 + 43N + 7, alg. is O(N2) • Concerned with asymptotic behavior • Can analyze • Best case – limited use • Average • Worst (default) – maximum # of ops. • E.g.: for (i = 0; i < N; i++) // linear search if (A[i] == searchValue) break; • Complexity of linear search? • O(N)

  4. Standard Library • Languages include data structure/algorithms • Java: ? • Java Collections Framework (ArrayList, TreeSet) • C++: Standard Template Library (string, list, set) • X.NET: .NET class library • Standard C++ includes C++ Standard Library • Standard Template Library (STL) – part of Standard Library that provides • Container classes implement DS/Alg • vector, deque, list • set, map, multiset, multimap • stack, queue, priority_queue • array, valarray, string, bitset (“near containers”) • Algorithms (not associated w/class) • accumulate • copy • sort

  5. Output: 7 4 9 3 1 Storage Containers (Vectors) • vector – indexing feature of array and can dynamically grow #include <vector> // Output elements of v for (size_t i = 0; i < v.size (); ++i) cout << v[i] << " “;

  6. Storage Containers (Vectors) • vector -- “super-array”; all familiar array algorithms work • Grow or shrink vectors (std::vector<Type>)

  7. Storage Containers (Vectors) • Vectors allow subscripting, but are inefficient storage structures for • insertions at arbitrary positions in a list • deletions at arbitrary positions in a list

  8. Shifting Elements

  9. Storage Containers (Lists) • list container (#include <list>) • Each element has reference that identifies the next (and previous) • Adding a new item -- breaking a link in the chain and creating two new links (O(1))

  10. Storage Containers (Maps, Sets) • maps and sets store keys (<set>, <map>) • Use a binary search tree to store data • Store data by key

  11. A BST Holding Airbill Numbers • N = 8 -- any search requires at most 3 movements along a path from the root

  12. Abstract Data Types • Specify DS/Alg using ADTs • ADT • Collection of values (integers) • Set of operations on the data with pre- and post-conditions (+, -, *, etc.) • In C++, we implement ADT’s with a class • Class encapsulates • Data – data members (Java: instance vars.) • Operations – member functions (Java: methods)

  13. Abstract Data Types ADT Operation Description • operationName: action statement specifies input parameters, type of operation on elements of data structure, and output parameter(s) • Preconditions: necessary conditions that must apply to input parameters and current state of object to allow successful execution of operation • Postconditions: changes in data of structure caused by operation

  14. Abstract Data Types(time24) • duration (t): Time t is input parameter of type time24. Measure length of time from this time to time t and return result as a time24 value • Precondition: Time t must not be earlier than the current time • Consider: Operation: 9 30 10 20 (a) ct.addTime (50) Time (Before) Time (After) Operation: 45 14 1 30 16 15 (b) ct.duration (t) Current Time Return time Time t

  15. Classes(To implement ADTs)

  16. Classes (Private/Public Sections) • public and private sections in a class definition allow program statements outside the class different access levels

  17. Classes (Private/Public Sections) • Public members of a class are the interface of the object to the program. • Any statement with access to an object can access a public member of the object

  18. Classes (Private/Public Sections) • Private section typically contains the data values of the object and utility (helper) functions that support class implementation • Only member functions of the class may access elements in the private section • Key to separate implementation from interface

  19. Scope Resolution Operator • Binary scope resolution operator: "::“ • Signals the compiler that the function is a member of class • Statements in the function body may access all of the public and private members of the class • The “::” operator allows you to code a member function like any other free function • Could also inline definition in class definition returnType className::functionName (argument list) { <C++ statements> }

  20. Class Example • Class “Rectangle” • Default constructor • default arguments • member initializers • Const member functions (cannot modify object) • Method definitions are inlined • Usu. separate header from implementation

  21. class Rectangle { public: // Ctor. Init length and width Rectangle(double length = 0.0, double width = 0.0) : m_length (length), m_width (width) {} Declaration CLASS Rectangle

  22. // Return area double area() const { return m_length * m_width; }   // Return perimeter double perimeter() const { return 2 * (m_length + m_width); } Declaration CLASS Rectangle

  23. // Change dimensions void setSides (double length, double width) { m_length = length; m_width = width; }   // Return length double getLength() const { return m_length; } Declaration CLASS Rectangle

  24. // return the width of the rectangle double getWidth() const { return m_width; } private: double m_length; double m_width; }; Declaration CLASS Rectangle

  25. APIs • Application Programming Interface (API) = ADT + syntax • Documentation from ADT and class declaration that captures key info • Function prototypes for all public member functions • Constructors usu. listed separately • Description of methods with pre- and post-conditions

  26. CLASS className Constructors “<file>.h” className (<arguments>); Initializes the attributes of the object Postconditions: Initial status of the object API(Constructor)

  27. CLASS className Operations “<file>.h” returnType functionName (argument list); Description of the action of the function and any return value Preconditions: Necessary state of the object before executing the operation. Any exceptions that are thrown when an error is detected. Postconditions: State of the data items in the object after executing the operation …. API (Operations)

  28. API Example • Random number class (not std C++) • Generate integer and real random #’s • Note API does not expose implementation

  29. CLASS RandomNumber Constructors RandomNumber (unsigned int seed = 0); Sets the seed for the random number generator Postconditions: With the default value 0, the system clock initializes the seed; otherwise the user provides the seed for the generator API (RandomNumber Class)

  30. CLASS RandomNumber Operations double frandom (); Return a real number x, 0.0 <= x < 1.0 int random (); Return a 32-bit random integer m, 0 <= m < 231-1 int random (unsigned int n); Return a random integer m, 0 <= m < n API (RandomNumber Class)

  31. Generating Random Numbers int item; double x; RandomNumber rndA, rndB; for (size_t i = 0; i < 5; ++i) { item = rndA.random (40); // 0 <= item < 40 x = rndB.frandom (); // 0.0 <= x < 1.0 cout << item << " " << x; }

  32. String Methods • Class string: useful member functions • find_first_of • find_last_of • find • substr • insert • erase • string::npos • Free operator+ to concatenate • Check string docs on course page • SGI link

  33. size_t find_first_of (char c, size_t start = 0): Look for the first occurrence of c in the string beginning at index start. Return the index of the match if it occurs; otherwise returns static_cast<size_t> (-1) which is string::npos. By default, start is 0 and the function searches the entire string. String Functions and Operations

  34. size_t find_last_of (char c): Look for the last occurrence of c in the string. Return the index of the match if it occurs; otherwise returns npos. Since the search seeks a match in the tail of the string, no starting index is provided. String Functions and Operations

  35. string substr (size_t start = 0, size_t count = npos): Copy count characters from the string beginning at index start and return the characters as a substring. If the tail of the string has fewer than count characters or count is npos, the copy stops at end-of-string. By default, start is 0 and the function copies characters from the beginning of the string. Also by default, the function copies the tail of the string. String Functions and Operations

  36. size_t find (const string& s, size_t start = 0): The search takes string s and index start and looks for a match of s as a substring. Return the index of the match if it occurs; otherwise return npos. By default, start is 0 and the function searches the entire string. String Functions and Operations

  37. string& insert (size_t start, const string& s): Place the substring s into the string beginning at index start. The insertion expands the size of the original string. String Functions and Operations

  38. string& erase (size_t start = 0, size_t count = npos): Delete count characters from the string beginning at index start. If fewer than count characters exist or count is npos, delete up to end-of-string. By default, start is 0 and the function removes characters from the beginning of the string. Also by default, the function removes the tail of the string. Note that no arguments truncate the string to the empty string with length 0 String Functions and Operations

More Related