380 likes | 548 Views
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
E N D
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
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
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)
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
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] << " “;
Storage Containers (Vectors) • vector -- “super-array”; all familiar array algorithms work • Grow or shrink vectors (std::vector<Type>)
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
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))
Storage Containers (Maps, Sets) • maps and sets store keys (<set>, <map>) • Use a binary search tree to store data • Store data by key
A BST Holding Airbill Numbers • N = 8 -- any search requires at most 3 movements along a path from the root
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)
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
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
Classes (Private/Public Sections) • public and private sections in a class definition allow program statements outside the class different access levels
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
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
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> }
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
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
// Return area double area() const { return m_length * m_width; } // Return perimeter double perimeter() const { return 2 * (m_length + m_width); } Declaration CLASS Rectangle
// 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
// return the width of the rectangle double getWidth() const { return m_width; } private: double m_length; double m_width; }; Declaration CLASS Rectangle
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
CLASS className Constructors “<file>.h” className (<arguments>); Initializes the attributes of the object Postconditions: Initial status of the object API(Constructor)
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)
API Example • Random number class (not std C++) • Generate integer and real random #’s • Note API does not expose implementation
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)
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)
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; }
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
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
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
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
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
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
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