Data Structures Midterm

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

Multiple inheritance

Allows subclasses to inherit from more than one superclass Can create problems if superclasses have a common ancestor in inheritance hierarchy

Pointer arithmetic

An offset can be added to the base address(*a) of the array: a+1, a+2, ... etc. and dereference the result. Ex. *(a+1)=a[1], *(a+2)=a[2], ... etc. As long as the value of a is not changed, this alternate approach can be used to access the array's elements

ADT Examples

Array, List, Map, Queue, Set, Stack, Table, Tree, and Vector are ADTs

Example of complexity(f(n)=n^2+100n+log10(n)+1000)

Consider f(n) = n^2 + 100n + log10(n) + 1000 As n increases, the significantterm goes: 1000->100n->n^2 (at large n, only n^2 is significant) So, n^2+100n+log10(n)+1000=O(n^2) (read "big-oh of n squared")

Vector

Container in STL where the elements are stored contiguously in memory and the entire structure is treated like a dynamic array Exhibit low memory utilization, good locality of reference, and good data cache utilization (Like dynamic arrays) Allow random access, so elements can be referenced using indices

Public, protected, or private in Subclass headers

Control amount of access, and level of modifications A subclass with public inheritance preserves the access classes of superclass A subclass with protected inheritance treats public and protected members of superclass as protected(private members remain private) Subclasses with private inheritance treat all members of superclass as private

Properties of Ω and Θ Notations

First four for big-O are true for Ω and Θ Replacing O with Ω and "largest" with "smallest" in the fifth theorem for big-O and it remains true f(n)=Ω(g(n)) when lim(n->∞)(g(n)/f(n))=constant f(n)=Θ(g(n)) when lim(n->∞)(f(n)/g(n))=constant≠0

Functionals

Functions that take functions as arguments

Different ways to describe Big-O notaion

Given f(n)=O(g(n)) f is big-O of g f will never go above g f is bound from above by g f grows slower than g

Pointers and Reference Variables

Given the declarations: int n=5; *p=&n; &r=n; A change to the value of n via any of the three will be reflected in the other two. Ex: n=7 or *p=7 or r=7 (All get the same result, the value of n is 7) So we can dereference a pointer, or use a reference directly to access the original object's value

Reference variable

Implemented as constant pointers that allow modification of values of arguments Can also be returned from a function(Pointers have to be dereferenced first)

Vectors and iterators

In addition to the traditional array notation, a vector's elements can be accessed using iterators This requires the dereferencing notation used for pointers

Singly Linked Lists Insertion

Inserting node at beginning: First, new node is created and info is initialized Next member initialized to point to 1st node (head) Head updated to point to new node Inserting node at end: New node is created and info is initialized Next member initialized to null (Bc node at end) Next of current last node set to point to new node Now new node is at end, so tail needs to point to it If list is initially empty, head/tail point to new node

Destructor

Member function automatically called when its associated object is deleted. It then frees the resources that the object may have acquired during its lifetime. It can specify special processing to occur, such as the deletion of pointer-linked memory objects Syntax: void destructor( ){} ~className( ); (in class) className::~className( ){} (in linked list) Ex: linked list className::~className( ){ Node* temp=head; while(temp!=NULL){ Node* ptr=temp->next; delete temp; temp=ptr; } delete head; delete tail; }

Dynamic binding in c++

Method declared "virtual", allowing the method to be selected based on the value the pointer has At run time

Static binding in c++

Method is chosen based on the pointer's type Allows the sending of messages to different objects without having to know any of the details of the receiver It is the receiving object's responsibility to determine how to handle the message At compile time

Function objects in STL

Set of classes that overload the function operator (operator()) Maintain state info in functions that are passed to other functions Regular function pointers can also be used as function objects

Limitations of arrays

Size of array must be known at compile time The elements of the array are the same distance apart in memory, requiring potentially extensive shifting when inserting a new element. Linked lists can be used instead

Overriding

Subclasses can add/delete/modify methods and data members in their own definitions

copy constructor Syntax and Example code

Syntax: ClassName (const ClassName &old_obj); Ex: #include<iostream> using namespace std; class Point { private: int x, y; public: Point(int x1, int y1) { x = x1; y = y1; } // Copy constructor Point(const Point &p2) {x = p2.x; y = p2.y; } int getX() { return x; } int getY() { return y; } }; int main() { Point p1(10, 15); // Normal constructor is called here Point p2 = p1; // Copy constructor is called here // Let us access values assigned by constructors cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY(); cout << "\np2.x = " << p2.getX() << ", p2.y = " << p2.getY(); return 0; }

Binding

The method called depends on the time at which the decision is made about the call in polymorphism Can occur in different ways: Static - determines the function call at compile time Dynamic - delays the decision until run time

Class

User defined data-type which has data members and member functions. When a class is defined, no memory is allocated but when it is instantiated(object is created) memory is allocated.

Limits for big-O, big-Ω, and Θ

Using lim(n->∞)(f(n)/g(n)): If lim=inf, f(n)=Ω(g(n)) If lim=c>0, f(n)=Θ(g(n)) If lim=0, f(n)=O(g(n))

Pointers and Destructors

When a local object goes out of scope, the memory associated with it is released but if one of the object members is a pointer, the pointer's memory is released, leaving the object pointed at inaccessible To avoid this memory leak, objects that contain pointers need to have destructors written for them

Problem with "big-O" notation

While c and N exist, does not tell how to calculate or what to do if multiple candidates exist (often do) Choose N so one term dominates the expression Ex. Consider the function f: f(n)=2n^2+3n+1 and g: g(n)=n^2 Clearly 2n^2+3n+1=O(n^2) or f(n)=O(g(n)); Only two terms to consider: 2n^2, 3n (last term is constant) When n>=1.5, 2n^2 dominates the expression (N>=2, and c>3.75) Main point of "big-O"(f(n)<=cg(n)) relies on the choices of c and N to be within the perimeters Choice of c depends on choice of N(vice-versa)

Using pointers to access dynamically created locations Syntax

int *p; p=new int; //p initialized then used in function delete p; p=NULL;

Singly Linked Lists Insertion Code

void LinkedList::insertAtHead(int value){ if (head == NULL){ head = new Node(); head->info = value; tail = head; } else{ Node* temp = new Node(); temp->info = value; temp->next = head; head = temp; } } void LinkedList::insertAtTail(int value){ if(head==NULL){ head = new Node(); head->info = value; tail = head; } else{ Node* temp= new Node(); temp->info = value; temp->next=NULL; tail->next=temp; tail=temp; } }

Singly Linked Lists search Code

void LinkedList::search(int value){ bool found = false; Node* temp = head; while(temp!=NULL){ if(temp->info==value){ found = true; break; } temp = temp->next; } if(found==true){ cout << "Value present in the Linked List" << endl; }else{ cout << "Value not present in the Linked List" << endl; } }

Pointers and Copy Constructors

A problem can arise when copying data from one object to another if one of the data members is a pointer The default behavior is to copy the items member by member Because the value of a pointer is an address, this address is copied to the new object Consequently the new object's pointer points to the same data as the old object's pointer, instead of being distinct To correct this, the user must create a copy constructor Member function(constructor) which initializes an object using another object of the same class. Copies not only the pointer, but the object the pointer points to

Pointers

A variable whose value is the address of another variable in memory Name is a user-defined name preceded by an asterisk (*) to show variable is a pointer Ex: *ptr; Two important attributes: value (what it stores) address (where it is) Type is the type of variable they point to Ex. int i=4; int *p=&i; so p's type is (*int)

Polymorphism

Ability to create objects of different types that respond to method calls having the same name They differ in that they respond according to type-specific behavior Means that a call to a member function will cause a different function to be executed depending on the type of object that invokes the function. Decision made with binding

Standard Template Library (STL)

Addition to c++ to add even more capabilities. Independent of containers, which significantly reduces the complexity of the library The results of the STL are achieved through using templates This allows the use of static binding polymorphism which is frequently more efficient

Container in STL

Although the number of possible organizations of this data is unlimited, only a few are practical and implemented in the STL A number of methods are common to all containers, while some are more specific to the container they are defined in

Complexity

An algorithm's complexity is a function describing the efficiency of the algorithm in terms of the amount of data the algorithm must process There are two main complexity measures of efficiency: Time and Space complexity For both, the importance is on the algorithm's asymptotic complexity When n (number of input items) goes to infinity, what happens to the algorithm's performance? (limit of n->inf)

Decision problem

Any arbitrary yes-or-no question on an infinite set of inputs

Iterator

Any object that, pointing to an element in a container, can iterate through those elements using a set of operators (with at least the increment (++) and dereference (*) operators). A pointer can point to elements in an array, and can iterate through them using the increment operator (++). Other kinds possible too. Ex. Each container type has a specific iterator type designed to iterate through its elements Reduce the complexity and execution time

Use Amortized Complexity anaysis to consider a dynamic array application where the size of the array is doubled each time it fills up.

Array reallocation may be required, so worst case insertion may be O(n) Since remaining insertions are done in constant time, sequence of n insertions can always be done in O(n) time. So, n insertions can be completed in O(n) time. So the amortized time per operation is O(n)/n=O(1)

Static declaration

Arrays in C++ are declared before they can be used which means the size of the array must be determined before it is used. Ex. int a[size]; This is wasteful if the array declared is too large, or a limitation if it's too small. Ex. You need a 5 element array and the declared array has a size of 3

Data structure Examples

Arrays, linked lists(or just lists), records(also called tuples/structs), objects

Best, Average, and Worst Cases

Best - algorithm takes the fewest number of steps Worst - algorithm takes max number of steps Average - falls between the extremes Weight number of steps that occur for a given input by the probability(p) of that input occurring, and sum this over the number of inputs: ∑(𝑖)(p(input(i))steps(input(i))) In probability theory, above equ. defines expected value(assumes probabilities can be determined and their distribution known) p is a probability distribution, so it satisfies two constraints: Function p is never negative Sum of all probabilities=1 Consider sequentially searching an unordered array to find a target value: Best/worst cases are: Best case - target value is found in the first cell Worst case - target value found in the last cell, or not at all (but searched entire array) Avg. case - consider probability of finding target Probability of finding target in any one location is 1/n (Assuming uniform distribution of n values). So target in 1st location is p=1/n, in 2nd is p=1/n, etc. Number of steps required to get to each location is the same as the location itself, so sum becomes: 1/n*(1+2+...+n) = (n+1)/2 If probabilities differ, then it is much more involved

Ω and Θ Notations compared to Big O

Big-O only gives upper bound of function Consider O(n^3): n^2=O(n^3) but O(n^2) is a more meaningful upper bound Need lower and same rate bounds Big-Ω-lower bound (function that grows more slowly than f(n)) Θ-tight bound (function that grows same rate as f(n))

Object example

ClassName ObjectName; or ClassName *objectname=new ClassName; Ex. Queue *q = new Queue;

Linked lists

Collection of independent memory locations (nodes) that store data and links to other nodes Moving between nodes is accomplished by following links, which are the addresses of nodes Many ways to implement linked lists, but the most common utilizes pointers(provide flexibility)

Θ Notation

Combines upper and lower bounds to get tight bound (intersection of O(f(n)) and Omega(f(n))) All Θ(f(n)) are O(f(n)), but not other way around Let f(n) and g(n) be functions, where n is pos int f(n)=Θ(g(n)) when g(n)=O(f(n)) and g(n)=Ω(f(n)). (read "f of n is theta of g of n.")

Possible Problems for complexity

Consider 2 alg.: one requires 10^8n=(O(n)) the other 10n^2=(O(n^2)) Big-O only: 2nd alg. rejected(grows too fast) Above only if n>107(often much smaller), so 2nd alg. would be faster than the 1st Consider other factors in analysis: "double-O" notation has been used in such cases f=OO(g(n)) (for f=O(g(n)) & c is too large) So 10^8n=OO(g(n))

Implementation of Singly Linked lists

Create .h file to declare classes node and linkedlist Node will declare info and next linkedlist declares all variables and functions used Create .cpp file to initialize all functions in linkedlist All of the functions' codes are here. Create main file that calls all the functions from the other two files and returns the outputs

Data structure

Data organization, management and storage format that enables efficient access and modification

Algorithms

Data structures are implemented using algorithms Some algorithms are more efficient than others which are preferred Use metrics to compare them(Complexity)

Amortized Complexity

Data structures can be manipulated by sequences of operations. So operations early in the sequence can impact performance later in the sequence. To determine overall performance, accumulate performance for each sequence to determine result(Can give inaccurate results) More useful approach: consider entire sequence of operations of program. Worst-case bound can be determined irrespective of the inputs by looking at all of the operations While some operations may be costly, they do not occur frequently enough to bias entire program. Because less costly operations will outnumber costly ones in the long run ("paying back" program over number of iterations) Useful because rather than assuming, it guarantees worst-case performance

Abstract Data Types (ADTs)

Defined indirectly, in terms of operations to be performed rather than in terms of its inner structure. Can then be implemented through class definitions in an object-oriented language

Message passing

Degree that objects interact is defined by communication methods

Singly Linked Lists Deletion

Deleting node consists of returning value stored in node and releasing memory occupied by node Delete at beginning: Retrieve value stored in the 1st node(head → info) Temp points to head & head points to head→next Former head deleted, memory released Two special cases when doing this deletion: List is empty (Notify function caller) Only one node in list (head/tail set to null) Deleting at end: (Back up tail to previous node in list) Can't be done directly, temp needed to traverse the list until temp → next = tail Retrieve the value contained in tail → info, delete that node, and set tail = temp Same special cases for deleting node from end

Space complexity

Describes the amount of memory (space) an algorithm takes in terms of the amount of input

Time complexity

Describes the amount of time an algorithm takes in terms of the amount of input

Principle of information-hiding

Details of implementation of objects can be hidden from other objects to prevent side effects from occurring That means every object used is independent of all other objects, unless a method is designed for communicating between objects

"Virtual"

Ex: Classes B and C inherit class A as "virtual" This treats A as a direct superclass of D(D was subclass of B and C) So only one copy of A is available to inherit (eliminates ambiguity)

"Big-O" notation

Formal method for expressing asymptotic upper bounds (growth of function bound from above) Let f(n) and g(n) be functions, where n = pos. int f(n)=O(g(n)) if there exists a real number(c) and pos. int(N) satisfying 0<=f(n)<=cg(n) (for n>=N). (read "f of n is big-oh of g of n.") Ex. n^2+n, 4n^2-nlog(n)+12 ,n^2/5-100n all =O(n^2)

Pointers and Function

Function's value is the result it returns Its address is the memory location of the function So a pointer can be used to point to a function to access it Given temp( ), temp(address) is a pointer to the function and *temp(value) is the function itself Using this we can implement functionals

NP-complete

Generally believed P ≠ NP, but still a famous open problem.(Belived bc NP-complete problems exist) Problem is reducible if every instance of it can be transformed into instances of another using a process referred to as a reduction algorithm If this transformation can be done efficiently (polynomial time), then efficient solutions of 2nd problem can be transformed into efficient solutions of the original problem Problem is NP-comp. when it's NP and all others in NP is reducible to the problem in polynomial time. (all NP-complete problems are equal) If NP-complete prob. solved with deterministic alg. all NP-complete prob. can be solved same way. If any NP is intractable, so are all NP-complete Reducibility process uses NP-comp prob to show another prob is NP-comp. But, has to be at least one prob proven to be NP-comp by means other than reducibility to make reduction possible

Algorithms in STL

Generic functions that perform operations where each is implemented to require a certain level of iterator (work on any container with interface by iterators) Algorithms are in addition to the methods provided by containers, but some algorithms are implemented as member functions for efficiency Operate through iterators directly on the values while never affecting the size or storage allocation of the container

NP-Completeness

Given an input, underlying algorithm has only one way to decide what step to perform at any point While, nondeterministic alg. uses operation to "guess" what to do next when a decision is made. (Can exhibit different behaviors on different runs) There are several ways this can happen Ex.concurrent alg. may experience race conditions Problems that can be solved by a deterministic alg. in polynomial time belong to class P. (tractable) If problem can be solved in polynomial time by a nondeterministic algorithm, it is of class NP. Tractable only if a nondeterministic alg. is used. "P"⊆NP (deterministic alg. are nondeterministic alg. that don't use nondeterministic decisions)

Singly Linked lists

If node contains pointer to another node, any number of nodes can be strung together(need only a single variable to access the sequence) Each node contains data and link to the next node Last node in the list has a null pointer ( \ ) Nodes have two data members: info - stores the node's info content (value) next - points to the next node in the list First node = head and last node = tail

Pointers and Arrays

In array notation, we access the elements of a by subscripting: a[0], a[1], ... etc. Can also dereference the pointer to achieve the same results: *a is equivalent to a[0] (other elements can be accessed using pointer arithmetic) A name of an array is nothing more than a label for the beginning of the array in memory, so it is a pointer An array can also be declared dynamically as long as the size is known when the declaration is executed

Finding Asymptotic Complexity(single loop)

Interest in time complexity(based on assgn. and comparisons in program) Consider this loop: for (i=sum=0; i<n; i++) sum = sum + a[i]; Initialization: Two assgn. executed once (sum=0&i=sum) Iteration: i++ executed n times In loop: sum=sum+a[i] executed n times Two executed once and two executed n times. So 2+2n assgn. in loop's execution and 2+2n=O(n)

Properties of Big-O Notation

Key: x=f(n), y=g(n), z=h(n) if x=O(y) and y=O(z), then x=O(z) If x=O(z) and y=O(z), then x+y=O(z) A function an^k=O(n^k) (for a>0) Any kth degree polynomial is O(n^k+j) (for j>0) x=O(y) is true if lim(n->∞) (x/y) is a constant (x=cy) loga(n)=O(logb(n)) (for any a, b>1). Means(except few cases) base of log doesn't matter. Instead use one base and rewrite as: loga(n)=O(lg(n)) (for pos a≠1 and lg(n)=log2(n))

How to delete specific node based on info?

Locate the specific node, then link around it by linking the previous node to the following node. To do this keep track of the previous node and keep track of the node containing the target value (requires two pointers) pred and temp initialized to 1st and 2nd nodes. They traverse list until temp→info==target value Set pred→next=temp→next ("bypasses" target node, deleting it) Several cases to consider with this deletion: Empty list or target value isnt in list Deleting the only node in the list Removing 1st or last node from list(nodes>1)

Disadvantage of single-linked lists

Longer the list, longer the chain of next pointers needed to be followed to a given node. This reduces flexibility and is prone to errors. Alternative is doubly linked lists

Constructor

Member function of a class which initializes objects of a class. Constructor is automatically called when a object is created Syntax: class className{ public: int a, b; //Data members int *ptr; constructorName(){ a=initialValue; b=initialValue; ptr=NULL; } }; //constructorName usualy =className int main() { className objectName; //Default constructor called automatically when the object is created return 0; }

Finding Asymptotic Complexity(nested loops)

Nested loops can grow complexity by a factor of n Consider this nested loop: for (i=0; i < n; i++) { for (j = 1, sum = a[0]; j <= i; j++) sum += a[j]; cout << "sum for subarray 0 through " << i <<" is "<<sum<<end1; } Outer loop: loop header: i initial one time i++ n times In loop: cout executed n times (doesn't count towards complexity) Inner loop: loop header: j set to value n times sum set to value n times <-Here 1+3n j++ i times In loop: sum += a[j]; executed i times <-Here 2i Inner loop executes i times where 1<=i<=(n-1) So it executes ∑(n-1)(𝑖=1)(2𝑖)=2(1+2+...+(n-1))=2n(n-1) Total number of assgn: 1+3n+2n(n-1)=O(1)+O(n)+O(n^2)=O(n^2) Not all loops increase complexity Additional complexity when number of iterations changes during execution. (The case more powerful searching and sorting alg.)

How to find N and c from "big O" problem Consider the function f: f(n)=2n^2+3n+1 and g: g(n)=n^2

Obtained by solving f(n)<=cg(n) with different N Substituting for f(n) and g(n): 2n^2+3n+1<=cn^2 or 2+3/n+1/n^2<=c Start with N=1 and subst. to obtain c (n>=N(pos)) Possible candidates for c and N: c: >=6 >=3(3/4) >=3(1/9) >=2(13/16) >=2(16/25)....-->2 N:1 2 3 4 5 ....-->infinity

Problem can arise with dynamic memory allocations (memory leak)

Occurs when the same pointer is used in consecutive allocations without being freed Ex: p = new int; p = new int; Since the second allocation occurs without deleting the first, the memory from the first allocation becomes inaccessible This leak can accumulate until no memory is available for further allocation To avoid this, memory needs to be deallocated when no longer in use (use delete; and =NULL when done)

Ω Notation

Opposite of Big O(vise-versa) Let f(n) and g(n) be functions, where n is pos int f(n)=Ω(g(n)) when g(n)=O(f(n)) (read "f of n is omega of g of n.") Since g is lower bound for f, after a certain n, f will never go below g (ignoring multiplicative const)

Problem with info hiding with pointers and ref var.

Possible to compromise information hiding, if a public method returns a reference to a private data member This reference, as an address, allows bypassing of the protection mechanisms provided in the class definition which results in data corruption.

Tractable

Problem that can be solved this way: Decision problems can be defined equivalently as the set of inputs for which the problem returns yes Nondeterministic alg. can solve decision problem if path in decision tree of alg. that leads to a "yes" answer exists (otherwise answer is "no") If number of steps in the decision tree path to the affirmative answer is O(n^k) (for n=size of specific problem), then algorithm is considered polynomial

Generic entities provided by STL

Provides generic entities: Containers, iterators, algorithms, function objects, and ready-made set of common classes for C++ (containers, associative arrays, etc.)

Public/private/protected

Public class members and functions can be used from outside of a class by any function or other classes. You can access them directly by using dot operator (.) or arrow operator(->)(pointers) Protected class members and functions can be used inside its class and by friend functions and classes. Protected members and functions cannot be accessed from other classes directly. Private class members and functions can be used only inside of class and by friend functions and classes.

Vectors in STL

Sequence container representing an array that can change in size Useful for storing lists with unknown length prior to setting it up but where removal is rare Adding new elements is easy, unless the size reaches capacity. To fix, resize the vector first.

Diamond problem (multiple inheritance)

Subclass inherits multiple copies of the same member(Possible errors like a compiler error) Ex: Two classes B and C inherit from A, and D inherits from B and C The problem occurs in the example if D uses a method(Not overridden) that is defined in A Solution: classes B and C inherit class A as "virtual"

Using "big O" notation on 3n^2+4n-2

Substitute f(n) and g(n) into f(n)<=cg(n) ,(g(n)=n^2): 3n^2+4n-2<=cn^2 (for n>=N) Divide by n^2: 3+4/n-2/n^2<=c Choose N so c can be found, then solve for c: N=1 3+4-2<=c so c>=5 Set c to 6 (>=5) in f(n)<=cg(n): 3n^2+4n-2<=6n^2 (for n>=1) So the function is O(n^2)

Inheritance

Technique of reusing existing class definitions to derive new classes. The new classes(called derived/sub/child classes) can inherit attributes and behavior of pre-existing classes(called base/super/parent classes) This relationship of classes through inheritance forms a hierarchy Information hiding can be extended through this hierarchy by the access the superclass allows the subclass(es) Subclasses can override in their own definitions

Types of iterators in STL

The STL implements five types of iterators: Input iterators - reads a sequence of values Output iterators - writes a sequence of values Forward iterators - can be read, written to, or moved forward Bidirectional iterators - behave like forward iterators but can also move backwards Random iterators - can move freely in any direction at one time Most Limited->Least Limited: Input/output->Forward->Bidirectional->Random

Data encapsulation

The combination of data members and methods in a class. Binds the data structure and its operations together in the class Program can then focus on manipulation of these objects through their associated methods

Advantages of Encapsulation

The strong link between data and operations better mimics real-world behavior, on which program models are based Implementation errors are confined to the methods of a class in which they occur, making them easier to detect and correct Allows principle of information-hiding

Using pointers to access dynamically created locations

Two functions that handle dynamic memory: new data_type; - Allocates memory which returns the address of the allocated memory, which can be assigned to a pointer delete pointername;(like free in c) - Releases the dynamically allocated memory pointed at.

Problem can arise with delete; (dangling reference problem)

When an object is deleted without modifying the value of the pointer, the pointer still points to the memory location of the deallocated memory Attempting to dereference the pointer will cause an error To avoid this, after deleting the object, the pointer should be set to a known address or NULL(0) Ex: delete p; p = NULL; or p = 0;

iterator operations and Examples

begin(),end(),next(),prev(),etc. Ex. int main() { vector<int> ar = { 1, 2, 3, 4, 5 }; //container vector<int>::iterator ptr; //Declaring iterator to a vector cout << "The vector elements are : "; for (ptr=ar.begin(); ptr<ar.end(); ptr++) cout <<*ptr<< " "; //Displaying vector elements using begin() and end() return 0; } Ex. int main() { vector<int> ar = { 1, 2, 3, 4, 5 }; //container vector<int>::iterator ptr = ar.begin(); vector<int>::iterator ftr = ar.end(); // Declaring iterators to a vector auto it=next(ptr, 3); //next() returns new iterator // points to 4 auto it1=prev(ftr, 3); //prev() returns new iterator // points to 3 cout<<"The pos of new iterator using next() is : "<<*it<<endl; cout << "The pos of new iterator using prev() is : "<<*it1<<endl; //displaying the new iterator positions return 0; }

Class Syntax

class Classname{ access specifier: //public, private or protected Data members; //Variables to be used Member functions(); //methods to access data members }; //ends with ";" after "}"

Example code of a singly linked list

class IntSLLNode { public: IntSLLNode() { next = 0; } IntSLLNode(int i, IntSLLNode *in = 0){ info = i; next = in; } int info; IntSLLNode *next; } Contains two constructors: One sets the next pointer to 0 and leaves info member undefined. Other initializes both members Uses two classes: IntSLLNode - defines the nodes of the list IntSLList - defines *head and *tail, as well as various member functions to manipulate the list Ex: class Node{ public: int info; Node* next; }; class Linked List{ public: Node* head, *tail; LinkedList(); ~LinkedList(); void insertAtHead(); void search(int value); void displayList(); };

Deleting dynamic arrays syntax

delete[ ] a; a=NULL; [ ] indicate that an array is to be deleted p is the pointer to that array

Syntax to declare an array dynamically

int *a; a = new int[size]; Each element in the array declared dynamically can now be accessed by the pointer pointing to the array by pointer arithmetic Ex: *a=25 1st element of a set to 25 *(a+3)=25; 4th element of a set to 25 cout<<*(a+3)<<endl; Outputs the 4th element of a(25)

Problems with Pointers and Reference Variables (const)

int *const - declares a constant pointer to an integer (Memory address constant) Causes errors if we attempt to assign a value through a dereferenced pointer Ex: int *const ptr1=&x; const int *- declares a pointer to a constant integer (Value pointed to constant) Causes errors if we attempt to assign a new value Ex: const int *ptr1=&x; const int * const- declares a constant pointer to a to a constant integer (Both memory address and value pointed to constant) Ex: const int * const ptr1=&x;

Basic pointer syntax

int *ptr; - defines ptr as an int pointer pointing to NULL ptr=&i; - Initialization of ptr, now ptr points to the memory address of i *ptr=20; - The value of the address ptr points to(i) is changed to 20 j=2* *p; - j now equals 2 multiplied by the value stored in the memory address ptr is pointing to cout<<ptr<<endl; - outputs ptr, where ptr reffers to the address ptr points to (endl the same as \n in c) cout<<*ptr<<endl; - outputs *ptr, where *ptr reffers to the value of the address ptr points to

Complexity table

n 10 10^2 constant (O(1)) 1(1usec) 1(1usec) logarithmic (O(log(n))) 3.3(3usec) 7(7usec) linear (O(n)) 10(10usec) 10^2(100usec) O(nlg(n)) 33.2(33usec) 664(664usec) Quadratic (O(n^2)) 10^2(100usec) 10^4(10msec) Cubic (O(n^3)) 10^3(1msec) 10^6(1sec) Exponential (O(2^n)) 1024(10msec) 10^30(10^17yr) Longer time down the table and from left to right

Preferred algorithms

n^k=O((1+ε)^n)) for pos k & ε (So all polynomials are bound from above by all exponentials) Algorithm run in polynomial time will eventually be preferable to one run in exponential time (log n)^ε=O(n^k) for pos k & ε (So logarithm^(any power) grows slower than polynomials) Run in logarithmic time will eventually be preferable to run in polynomial(or exponential) time So slow growth and lower bounds are preferred

Self-referential objects

next points to node of same type being defined

Vector member functions

void assign(iterator first, iterator last); Remove all the elements in the vector and insert in it the elements from the range of first to last Ex: v4.assign(a,a+3); void assign(size_type n, const T& el = T( )); Remove all elements in the vector and insert in it n copies of el Ex: v4.assign(3,8); T& at(size_type n); or const T& at(size_type n) const; Return the element in n position of the vector T& back( ); or const T& back( ) const; Return the last element of the vector

Container

A data structure that is typically designed to hold objects of the same type. Ex. list,array,vector,etc. Implemented as class templates whose methods specify operations on the data in the structures as well as the structures themselves. The data stored in containers can be of any type and must supply some basic methods and operations

Object

A data structure, combined with the operations pertinent to that structure. Most object-oriented languages define objects through the use of a class

Example of vector member functions with c++

#include <iostream> #include <vector> #include <algorithm> #include <functional> // greater<T> using namespace std; template<class T> void printVector(char *s, const vector<T>& v){ cout<<s<<"=("; if(v.size( )==0){ cout<<")\n"; return; } typename vector<T>::const_iterator i=v.begin( ); for( ; i!=v.end( )-1; i++) cout<<*i<<' '; cout<<*i<<")\n"; } bool f1(int n){ return n<4; } int main( ){ int a[ ]={1,2,3,4,5}; vector<int> v1; //v1 is empty, size=0, capacity=0 printVector("v1",v1); for(int j=1; j<=5; j++) v1.push_back(j); //v1 = (1 2 3 4 5), size=5, capacity=8 vector<int> v2(3,7); //v2 = (7 7 7) vector<int>::iterator i1 = v1.begin( )+1; vector<int> v3(i1,i1+2); //v3 =(2 3), size=2, cap=2 vector<int> v4(v1); //v4=v1, size=5, cap=5 vector<int> v5(5); //v5=(0 0 0 0 0) v5[1] = v5.at(3) = 9; //v5=(0 9 0 9 0) v3.reserve(6); //v3=(2 3), size=2, cap=6 v4.resize(7); //v4=(1 2 3 4 5 0 0),size=7, cap=10 v4.resize(3); //v4=(1 2 3),size=3, cap=10 v4.clear(); //v4=empty,size=0,cap=10(!) v4.insert(v4.end( ), v3[1]); //v4=(3) v4.insert(v4.end( ), v3.at(1)); //v4=(3 3) v4.insert(v4.end( ),2,4); //v4=(3 3 4 4) v4.insert(v4.end( ),v1.begin( )+1,v1.end( )-1); //v4=(3 3 4 4 2 3 4) v4.erase(v4.end( )-2); //v4=(3 3 4 4 2 4) v4.erase(v4.begin( ),v4.begin( )+4); //v4=(2 4) v4.assign(3,8); //v4=(8 8 8) v4.assign(a,a+3); //v4=(1 2 3) vector<int>::reverse_iterator i3=v4.rbegin( ); for( ;i3!=v4.rend( ); i3++) cout<<*i3<<' '; //print: 3 2 1 cout<<endl; //algorithms: v5[0]=3; //v5= (3 9 0 9 0) replace_if(v5.begin( ), v5.end( ),f1,7); //v5= (7 9 7 9 7) v5[0]=3; v5[2]=v5[4]=0; //v5= (3 9 0 9 0) replace(v5.begin( ), v5.end( ),0,7); //v5= (3 9 7 9 7) sort(v5.begin( ), v5.end( )); //v5= (3 7 7 9 9) sort(v5.begin( ), v5.end( ), greater<int>( )); //v5= (9 9 7 7 3) v5.front( )=2; //v5= (2 9 7 7 3) return 0; }

Vector syntax

#include <vector> //vector library vector<dataType> vectorName; //Declaring vector vector<dataType> vecName(size); //Providing size vecName.push_back(value); //Adding item to vec vecName[index]; //Access index of a vector vecName[index]=value; //Change value at index Ex. using namespace std; vector<int> powersOfTwo; //Declaration powersOfTwo.push_back(1); //adding members powersOfTwo.push_back(0); powersOfTwo.push_back(4); powersOfTwo.push_back(8); cout << "2 ^ 3 = " << powersOfTwo[3]; //accessing powersOfTwo[1] = 2; //accessing and changing


Set pelajaran terkait

Chapter 3 Policies, Procedures, and Awareness

View Set

UNCC BLAW exam 3 (8,9,10,20,34,35)

View Set

Chapter 5 Therapeutic Relationships NCLEX

View Set

History, Chapter 1, Unit 1, 1.06 The Nile River Valley

View Set

study guide flash cards: cog exam 3

View Set