Introduction to ADTs
|
|
- Sandra Williamson
- 6 years ago
- Views:
Transcription
1 Data Structure Introduction to ADTs A particular way of storing and organizing data in a computer so that it can be used efficiently *from Wikipedia A set of data values and associated operations that are precisely specified independent of any particular implementation. *from A data type having - A specific, physical or logical representation of the data - Operations over its data A concrete and logical description May be implemented in various ways - Implementation-dependent Data abstraction refers to, providing only essential information to the outside world and hiding their background details, i.e., to represent the needed information in program without presenting the details. Data abstraction is a programming (and design) technique that relies on the separation of interface and implementation. Example Let's take one real life example of a TV, which you can turn on and off, change the channel, adjust the volume, and add external components such as speakers, VCRs, and DVD players, BUT you do not know its internal details, that is, you do not know how it receives signals over the air or through a cable, how it translates them, and finally displays them on the screen. Thus, we can say a television clearly separates its internal implementation from its external interface and you can play with its interfaces like the power button, channel changer, and volume control without having zero knowledge of its internals. Spring 2018 CS Husain Gholoom Page 1
2 Example Your program can make a call to the sort() function without knowing what algorithm the function actually uses to sort the given values. In fact, the underlying implementation of the sorting functionality could change between releases of the library, and as long as the interface stays the same, your function call will still work. In C++, we use classes to define our own abstract data types (ADT). You can use the cout object of class iostream to stream data to standard output like this: #include <iostream> using namespace std; int main( ) cout << "Hello C++" <<endl; return 0; Here, you don't need to understand how cout displays the text on the user's screen. You need to only know the public interface and the underlying implementation of cout is free to change. Access Labels Enforce Abstraction: In C++, we use access labels to define the abstract interface to the class. A class may contain zero or more access labels: Members defined with a public label are accessible to all parts of the program. The data-abstraction view of a type is defined by its public members. Members defined with a private label are not accessible to code that uses the class. The private sections hide the implementation from code that uses the type Spring 2018 CS Husain Gholoom Page 2
3 Data Abstraction Example: Any C++ program where you implement a class with public and private members is an example of data abstraction. Consider the following example: #include <iostream> using namespace std; class Adder public: // constructor Adder(int i = 0) total = i; ; // interface to outside world void addnum(int number) total += number; // interface to outside world int gettotal() return total; ; private: // hidden data from outside world int total; int main( ) Adder a; a.addnum(10); a.addnum(20); a.addnum(30); cout << "Total " << a.gettotal() <<endl; return 0; When the above code is compiled and executed, it produces the following result: Total 60 Above class adds numbers together, and returns the sum. The public members addnum and gettotal are the interfaces to the outside world and a user needs to know them to use the class. The private member total is something that the user doesn't need to know about, but is needed for the class to operate properly. Spring 2018 CS Husain Gholoom Page 3
4 Benefits of ADT's. ADTs have several benefits: o o o o o o Simplicity: Client programmer does not have to be concerned with details that underlie the implementation of the ADT (eg keeping track of the front and back of a queue) Modularity - Reliability: Dividing a system into components or modules, each of which can be designed, implemented, tested, reasoned about, and reused separately from the rest of the system. Abstractions : Omitting or hiding low-level details with a simpler ideas Encapsulation: Building walls around a module (a hard shell or capsule) so that the module is responsible for its own internal behavior, and bugs in other parts of the system can t damage its integrity. Flexibility for client programmer: can choose from among several implementations of an ADT Example: array stack for efficient time and space Or linked stack for flexibility Independence: ADT programmer can change implementations of ADT without forcing client to change. Data Structures Again The term data structures is often extended to include both concrete AND logical descriptions of complicated data types. A list of data structures could include ADTs - arrays - linked lists - stacks - queues - vectors or lists Spring 2018 CS Husain Gholoom Page 4
5 ADTs and Program Design ADTs are an important part of bottom up program design In practice, programs are built using a combination of top down and bottom up approaches: o Top down: Decompose problem into subproblems, then decompose subproblems. Repeat until subproblems are simple Structure charts are a common design tool o Bottom up Design a set of tools and use them to build a solution the problem The tools are the values and operations of ADTs Designing ADTs is an essential part of bottom up design ADT Operations Categories Declare a variable of the type o (ie using a type defined in the package) Allocate a variable of the type o May be done by a declaration o Or may require a special operation (eg new or constructor-like call ) Operations on values (ie procedures and functions that have values of the type as parameters): o Query a property of the value or the status of a value or a component of a value o Modify a value (ie through an in/out parameter) o Combining two or more values and return a new value (of the same or different type) o Comparing two or more values o Convert a value to a string o Input/output of values Iterate through subcomponents Spring 2018 CS Husain Gholoom Page 5
6 Commonly used ADTs The purpose of many commonly used ADTs is to: - Store a collection of objects - Potentially organize the objects in a specific way - Provide potentially limited access to the objects These ADTs are often called - Containers - Collections - Container classes The ADT Basic Collections are : There are three basic collections. The basic collection is often called a bag. It stores objects with no ordering of the objects and no restrictions on them. Another unstructured collection is a set where repeated objects are not permitted: it holds at most one copy of each item. A set is often from a predefined universe. A collection where there is an ordering is often called a list. Specific examples include an array, a vector and a sequence. These have the same idea, but vary as to the methods they provide and the efficiency of those methods. Other Examples : - Stack and Queue - Tree - Map (or dictionary) Spring 2018 CS Husain Gholoom Page 6
7 A List ADT Values: ordered (1st, 2nd, etc) set of objects Operations: - constructor: creates an empty list - isempty: is the list empty - size: returns the number of elements - add an element to the end of the list - remove an element i from the list - return the element at position i - change the element at position (to another value) A Set ADT Values: collection of unique objects Operations: A Map ADT - constructor: creates an empty set - isempty: is the set empty - size: returns the number of elements - add an element to the set (if not there) - remove an element from the set (if it is there) - iselement(x): true if x is in the set - union: combine two sets into one A collection of unique keys and a collection of values where each key is associated with a single value. Keys have one type, values another. Operations may include: constructor: creates an empty map isempty: returns true if map has no key-value pairs size: returns the number of key-value pairs in the map get(k): returns value associated with key k (if any) put(k,v): associates value v with key k (adds a pair) keyset: returns a set of all the keys in the map Spring 2018 CS Husain Gholoom Page 7
8 A Bag (multi-set) ADT A bag is an ADT or abstract data type defines a way of storing data: it specifies only how the ADT can be used and says nothing about the implementation of the structure. The bag values are unordered collection of objects (may include duplicates) The Bag ADT might have: accessor methods such as size, count Occurrence, possibly an iterator (which steps through all the elements). modifier methods such as add, remove, and addall. A union method which combines two bags to produce a third. The Bag ADT Operations : Inside the bag are some elements, values, or numbers. When you first begin to use a bag, the bag will be empty ( called initial state ) Numbers may be inserted into a bag. The bag can hold many numbers We can even insert the same numbers more than once We may ask about the contents of the bag. We may remove a numbers from a bag. But we remove only one number at a time. We can determine how many numbers are in a bag. Spring 2018 CS Husain Gholoom Page 8
9 Summary of the Bag Operations: - constructor: creates an empty bag - isempty: is the bag empty - size: returns the number of elements - add an element to the bag - remove an element from the bag (if it is there) - removes all copies of an element from the bag - occurrences(x): how many times x is in the bag Implementing an ADT Interface : Implementation : - class declaration - prototypes for the operations - data members for the actual representation - ( *.h ) - function definitions for the operations - depends on data members (their representation) - ( *.cpp ) Spring 2018 CS Husain Gholoom Page 9
10 Example ADT: Bag Version - 1 bag.h class Bag public: Bag (); void insert(int element); void remove(int element); int occurrences(int element) const; bool isempty() const; int size() const; static const int CAPACITY = 20; ; private: int data[capacity]; int count; concrete representation Note : Member variables of a class can be made static by using the static keyword. Static member variables only exist once in a program regardless of how many class objects are defined! Spring 2018 CS Husain Gholoom Page 10
11 Example ADT: Bag Version - 1 bag.cpp #include "bag.h" #include <cassert> using namespace std; Bag::Bag () count = 0; void Bag::insert(int element) assert (count < CAPACITY); data[count] = element; count++; // what does this do? void Bag::remove(int element) int index = -1; for (int i=0; i<count && index==-1; i++) if (data[i]==element) index = i; if (index!=-1) data[index] = data[count-1]; count--; int Bag::occurrences(int element) const int occurrences=0; for (int i=0; i<count; i++) if (data[i]==element) occurrences++; return occurrences; bool Bag::isEmpty() const return (count==0); int Bag::size() const return count; Note : #include <cassert> is a header file in the standard library of the C programming. The macro implements an assertion, which can be used to verify assumptions made by the program and print a diagnostic message if this assumption is false. Spring 2018 CS Husain Gholoom Page 11
12 Bag - driver bagtest.cpp #include<iostream> #include "Bag.h" using namespace std; int main() Bag b; cout << "\nis empty " << b.isempty() << endl ; b.insert(4); b.insert(8); b.insert(4); cout << "is empty " << b.isempty() << endl << endl ; cout << "size " << b.size() << endl ; cout << "how many 4's: " << b.occurrences(4) << endl << endl; b.remove(4); cout << "removed a 4" << endl; cout << "size " << b.size() << endl; cout << "how many 4's: " << b.occurrences(4) << endl << endl; Bag c(b); cout << "copied to c" << endl; cout << "size " << c.size() << endl; cout << "how many 4's: " << c.occurrences(4) << endl << endl; b.insert(10); cout << "added 10 to b" << endl; cout << "b.size " << b.size() << endl; cout << "c.size " << c.size() << endl << endl; cout << "starting insert of 20 items" << endl; for (int i = 0; i < 20; i++) b.insert(33); cout << "inserted 20 more items into b" << endl; return 0; Spring 2018 CS Husain Gholoom Page 12
13 Bag driver : output output of running bagtest is empty 1 is empty 0 size 3 how many 4's: 2 removed a 4 size 2 how many 4's: 1 copied to c size 2 how many 4's: 1 added 10 to b b.size 3 c.size 2 starting insert of 20 items assertion "count < CAPACITY" failed: file "../bagimp.cpp", line 17, function: void Bag::insert(int) 0 [main] 3358-L5-Bag 4412 cygwin_exception::open_stackdumpfile: Dumping stack trace to L5-Bag.exe.stackdump One way to resolve is to increase the size of the array Bag Version 1 - Summary Implemented using a fixed size array When adding more elements than fit in the bag, the program exits. One Solution : increase the size of the array in bag.h Better Solution: - use a dynamically allocated array - when its capacity is reached, allocate a new, bigger array. Spring 2018 CS Husain Gholoom Page 13
14 Bag Version -2 : Using Dynamic Memory Allocation bag.h class Bag public: Bag (); Bag(const Bag &); // The big three (constructor destructor and operator= ) ~Bag(); void operator=(const Bag &); void insert(int element); void remove(int element); int occurrences(int element) const; bool isempty() const; int size() const; static const int INCREMENT = 20; ; private: int *data; //pointer to bag array // concrete representation int capacity; //size of the array int count; //number of elements currently in array Spring 2018 CS Husain Gholoom Page 14
15 Bag Version - 2 bag.cpp Bag::Bag () count = 0; capacity = INCREMENT; data = new int[capacity]; //copy constructor Bag::Bag(const Bag &rhs) data = new int[rhs.capacity]; //allocate new array capacity = rhs.capacity; //copy values count = rhs.count; for (int i=0; i<count; i++) data[i] = rhs.data[i]; //desctructor Bag::~Bag() delete [] data; void Bag::operator=(const Bag &rhs) if (data) delete [] data; //delete old array data = new int[rhs.capacity]; //allocate new array capacity = rhs.capacity; count = rhs.count; for (int i=0; i<count; i++) data[i] = rhs.data[i]; //copy values void Bag::insert(int element) //if count is at the capacity, resize if (count==capacity) capacity += INCREMENT; int *newdata = new int[capacity]; //new array for (int i=0; i<count; i++) //copy values newdata[i] = data[i]; delete [] data; //delete old array data = newdata; //make data point to new data[count] = element; //add new element count++; // no changes to remaining functions! Spring 2018 CS Husain Gholoom Page 15
16 bag driver : output version 2 output of running bagtest is empty 1 is empty 0 size 3 how many 4's: 2 removed a 4 size 2 how many 4's: 1 copied to c size 2 how many 4's: 1 added 10 to b b.size 3 c.size 2 starting insert of 20 items inserted 20 more items into b resizing succeeded! Spring 2018 CS Husain Gholoom Page 16
17 Bag Implementation Using Vector - Summary of the Operations: - constructor: creates an empty bag - drop : add a number to the bag - pick: erase an element from the bag - get_size : returns the number of elements - get_capacity : returns cap - display : display numbers - is_full : is the bag full - subtract : erase common numbers from 2 bags Spring 2018 CS Husain Gholoom Page 17
18 Vector Bag Implementation - bagvector.h #ifndef BAGVECTOR_H_ #define BAGVECTOR_H_ #include <iostream> #include <vector> using namespace std; class My_Bag private: const static int DS=5; vector<int> b; unsigned int cap; unsigned int size; public: My_Bag(); My_Bag(int); bool drop(int); bool pick(int); int get_size(); int get_capacity(); void display(); bool is_full(); bool subtract(const My_Bag&); ; bool My_Bag::subtract(const My_Bag& q) if (size==0 cap==0) return true; for (int i=0;i<q.b.size();i++) pick(q.b[i]); return true; Spring 2018 CS Husain Gholoom Page 18
19 Vector Bag Implementation ( cont. ) : My_Bag::My_Bag() cap=ds; size=0; My_Bag::My_Bag(int c) if (c<=0) cap=ds; else cap=c; size=0; bool My_Bag::drop(int item) if (size==cap) return false; b.push_back(item); ++size; return true; bool My_Bag::pick(int item) int index=-1; for (unsigned int i=0;i<size;i++) if (b[i]==item) index=i; b.erase(b.begin()+index); --size; return true; return false; int My_Bag::get_size() return size; Spring 2018 CS Husain Gholoom Page 19
20 Vector Bag Implementation ( cont. ) : int My_Bag::get_capacity() return cap; bool My_Bag::is_full() if (size==cap) return true; else return false; void My_Bag::display() cout << "Bag capacity: " << cap << endl; cout << "Current size: " << size << endl; for(unsigned int i=0;i<size;i++) cout << b[i] << ' '; cout << endl; #endif /* BAGVECTOR_H_ */ Spring 2018 CS Husain Gholoom Page 20
21 Vector Bag Implementation ( cont. ) : bagvectordriver.cpp #include <iostream> #include <vector> #include "bagvector.h" using namespace std; int main() My_Bag b1(5); b1.drop(10); b1.drop(10); b1.drop(20); b1.pick(10); b1.drop(20); b1.drop(30); b1.drop(10); b1.pick(20); b1.drop(-100); b1.drop(-100); b1.pick(10); b1.pick(10); b1.pick(30); b1.pick(-1009); b1.drop(20); b1.display(); cout << "==================\n"; Spring 2018 CS Husain Gholoom Page 21
22 bagvectordriver.cpp - ( continued ) My_Bag b2(10); b2.drop(20); b2.drop(20); b2.drop(30); b2.drop(78); b1.subtract(b2); b1.display(); cout << "==================\n"; b2.drop(-100); b2.drop(20); b2.subtract(b1); b2.display(); cout << "==================\n"; b2.drop(10); b1.subtract(b2); b1.display(); cout << "==================\n"; b1.drop(20); b2.subtract(b1); b2.display(); cout << "==================\n"; return 0; Spring 2018 CS Husain Gholoom Page 22
23 Sample Run Bag capacity: 5 Current size: ================== Bag capacity: 5 Current size: ================== Bag capacity: 10 Current size: ================== Bag capacity: 5 Current size: ================== Bag capacity: 10 Current size: ================== Spring 2018 CS Husain Gholoom Page 23
24 ADT - Example -2 : Rolling a Pair of Dice Write a function that rolls a pair of dice until the sum of numbers rolled is a specific number. Also, calculate the number of times the dice are rolled to get the desired sum. Note that the smallest number in each die is 1 and the largest number is 6. So, the smallest sum of the numbers rolled is 2 and the largest sum of the numbers rolled is 12. Use the random number generator to randomly generate a number between 1 and 6 by using the following formula for both die1 and die2 :- die1 = rand() % 6 + 1; die2 = rand() % 6 + 1; sum = die1 + die2; Spring 2018 CS Husain Gholoom Page 24
25 Solution : Rolling a Pair of Dice die.h class die public: die(); //Default constructor //Sets the default number rolled by a die to 1 int roll(); //Function to roll a die. //This function uses a random number generator to randomly //generate a number between 1 and 6, and stores the number //in the instance variable num and returns the number. int getnum() const; //Function to return the number on the top face of the die. //Returns the value of the instance variable num. private: int num; ; Spring 2018 CS Husain Gholoom Page 25
26 die.cpp //Implementation File for the class clocktype #include <iostream> #include <cstdlib> #include <ctime> #include "die.h" using namespace std; die::die() num = 1; srand(time(0)); int die::roll() num = rand() % 6 + 1; return num; int die::getnum() const return num; Spring 2018 CS Husain Gholoom Page 26
27 diedriver.cpp //The user program that uses the class rolldie #include <iostream> #include "die.h" using namespace std; int main() die die1; die die2; int sum ; int rollcount = 0; cout << "die1: " << die1.getnum() << endl; cout << "die2: " << die2.getnum() << endl; sum = die1.getnum() + die2.getnum(); cout << "die1 + die2 = " << sum << endl; do cout << "After rolling die1: " << die1.roll() << endl; cout << "After rolling die2: " << die2.roll() << endl; cout << "The sum of the numbers rolled" << " by the dice is: " << die1.getnum() + die2.getnum() << endl; rollcount ++; while ( ( die1.getnum() + die2.getnum() )!= sum); cout << endl; cout << "The number of times the Dice was rolled = " << rollcount<<endl; return 0; //end main Spring 2018 CS Husain Gholoom Page 27
28 Sample Run die1: 1 die2: 1 die1 + die2 = 2 After rolling die1: 5 After rolling die2: 1 The sum of the numbers rolled by the dice is: 6 After rolling die1: 3 After rolling die2: 3 The sum of the numbers rolled by the dice is: 6 After rolling die1: 4 After rolling die2: 3 The sum of the numbers rolled by the dice is: 7 After rolling die1: 1 After rolling die2: 1 The sum of the numbers rolled by the dice is: 2 The number of times the Dice was rolled = 4 Spring 2018 CS Husain Gholoom Page 28
29 C++ STL: Standard Template Library A library of ADTs implemented in C++ Two categories of STL ADTs: o containers: classes that store a collection of data and impose some organization on it. It include sequence containers and associative containers. sequence containers: organize and access data sequentially, as in an array such as vector, deque, and list. associative containers: use keys to allow data elements to be quickly accessed. These include set, map ( map set of values to key must be unique ),and multimap ( same as map but it allows duplicate keys. o iterators: behave like pointers; a mechanism for accessing elements in a container the iterator is associated with. STL Iterators: iterators: Generalizations of pointers, used to access data stored in containers. They point to a certain value (or the past-the-end element). They may be dereferenced with *. Some types of iterators: - forward: uses ++ to advance to next element. - bidirectional: uses ++ and random access: uses ++ and -- and uses [i] to jump to a specific element. Some vector member functions begin(): returns an iterator pointing to the vector s first element. end(): returns an iterator pointing to the vector s past the end element erase(iter): Removes from the vector either the single element the iterator argument is referring to. erase reduces the vector size by 1. Spring 2018 CS Husain Gholoom Page 29
30 Sample code using vectors and iterators #include <iostream> #include <vector> // Include the vector header using namespace std; int main() int count; // Loop counter vector<int> vect; // Define a vector of int object vector<int>::iterator iter; // Defines an iterator object // Use push_back to push values into the vector. for (count = 0; count < 10; count++) vect.push_back(count); // Step the iterator through the vector to display: cout << "The values in vector :\n\n" ; for (iter = vect.begin(); iter < vect.end(); iter++) cout << *iter << " "; // Step the iterator through the vector backwards. cout << "\n\nand here they are backwards:\n\n"; for (iter = vect.end() - 1; iter >= vect.begin(); --iter) cout << *iter << " "; // erase the 6th element vect.erase (vect.begin()+5); //advances 5 times cout << "\n\nvector contains:\n\n"; for (int i=0; i< vect.size(); i++) cout << ' ' << vect[i]; cout << endl; The values in vector : and here they are backwards: vector contains: Spring 2018 CS Husain Gholoom Page 30
31 C++ Standard Template Library and Standard Library contain components such as : <array> <deque> New in C++11 and TR1. Provides the container class template std::array, a container for a fixed sized array. Provides the container class template std::deque, a double-ended queue. <forward_list> New in C++11 and TR1. Provides the container class template std::forward_list, a singly linked list. <list> <map> <queue> <stack> Provides the container class template std::list, a doubly linked list. Provides the container class templates std::map and std::multimap, sorted associative array and multimap. Provides the container adapter class std::queue, a single-ended queue, and std::priority_queue, a priority queue. Provides the container adapter class std::stack, a stack. <unordered_map> New in C++11 and TR1. Provides the container class template std::unordered_map and std::unordered_multimap, hash tables. <vector> Provides the container class template std::vector, a dynamic array. <algorithm> Provides definitions of many container algorithms such as sorting, searching. <iterator> Provides classes and templates for working with iterators. <string> <regex> Provides the C++ standard string classes and templates. New in C++11. Provides utilities for pattern matching strings using regular expressions. Spring 2018 CS Husain Gholoom Page 31
32 <fstream> Provides facilities for file-based input and output. See fstream. <iomanip> Provides facilities to manipulate output formatting, such as the base used when formatting integers and the precision of floating point values. <istream> Provides the template class std::istream and other supporting classes for input. <ostream> Provides the template class std::ostream and other supporting classes for output. <exception> Provides several types and functions related to exception handling, including std::exception, the base class of all exceptions thrown by the Standard Library. <thread> <mutex> New in C++11. Provide class and namespace for working with threads. New in C This section provides mechanisms for mutual exclusion: ( mutexes, locks, and call once. or exception) from a function that has run in the same thread or another thread. <complex> The header <complex> defines a class template, and numerous functions for representing and manipulating complex numbers. Spring 2018 CS Husain Gholoom Page 32
33 Exercise Give an ADT Temperature. The data includes high and low temperature values. Give an ADT Temperature. The data includes high and low temperature values for 10 days. Give an ADT Temperature. The data includes high and low temperature values for any number of days. Spring 2018 CS Husain Gholoom Page 33
Introduction to ADTs
Data Structure Introduction to ADTs A particular way of storing and organizing data in a computer so that it can be used efficiently *from Wikipedia A set of data values and associated operations that
More informationIII. Classes (Chap. 3)
III. Classes III-1 III. Classes (Chap. 3) As we have seen, C++ data types can be classified as: Fundamental (or simple or scalar): A data object of one of these types is a single object. int, double, char,
More informationLinked Lists. Linked list: a collection of items (nodes) containing two components: Data Address (link) of the next node in the list
Linked Lists Introduction : Data can be organized and processed sequentially using an array, called a sequential list Problems with an array Array size is fixed Unsorted array: searching for an item is
More informationLinked Lists. Linked list: a collection of items (nodes) containing two components: Data Address (link) of the next node in the list
Linked Lists Introduction : Data can be organized and processed sequentially using an array, called a sequential list Problems with an array Array size is fixed Unsorted array: searching for an item is
More informationChapter 15 - C++ As A "Better C"
Chapter 15 - C++ As A "Better C" Outline 15.1 Introduction 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.4 C++ Standard Library 15.5 Header Files 15.6 Inline Functions 15.7 References and Reference
More informationCSCE 110 PROGRAMMING FUNDAMENTALS
CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class Prof. amr Goneid, AUC 1 Dictionaries(1): A Key Table Class Prof. Amr Goneid, AUC 2 A Key Table
More informationReview Questions for Final Exam
CS 102 / ECE 206 Spring 11 Review Questions for Final Exam The following review questions are similar to the kinds of questions you will be expected to answer on the Final Exam, which will cover LCR, chs.
More informationSTL components. STL: C++ Standard Library Standard Template Library (STL) Main Ideas. Components. Encapsulates complex data structures and algorithms
STL: C++ Standard Library Standard Template Library (STL) Encapsulates complex data structures and algorithms is a library of generic container classes which are both efficient and functional C++ STL developed
More informationTDDD38 - Advanced programming in C++
TDDD38 - Advanced programming in C++ STL II Christoffer Holm Department of Computer and information science 1 Iterators 2 Associative Containers 3 Container Adaptors 4 Lambda Functions 1 Iterators 2 Associative
More informationC++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay
C++ Basics Data Processing Course, I. Hrivnacova, IPN Orsay The First Program Comments Function main() Input and Output Namespaces Variables Fundamental Types Operators Control constructs 1 C++ Programming
More informationUnit 1: Preliminaries Part 4: Introduction to the Standard Template Library
Unit 1: Preliminaries Part 4: Introduction to the Standard Template Library Engineering 4892: Data Structures Faculty of Engineering & Applied Science Memorial University of Newfoundland May 6, 2010 ENGI
More informationCSC 222: Computer Programming II. Spring 2004
CSC 222: Computer Programming II Spring 2004 Stacks and recursion stack ADT push, pop, top, empty, size vector-based implementation, library application: parenthesis/delimiter matching run-time
More informationPurpose of Review. Review some basic C++ Familiarize us with Weiss s style Introduce specific constructs useful for implementing data structures
C++ Review 1 Purpose of Review Review some basic C++ Familiarize us with Weiss s style Introduce specific constructs useful for implementing data structures 2 Class The Class defines the data structure
More informationAbsolute C++ Walter Savitch
Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents
More informationSTL: C++ Standard Library
STL: C++ Standard Library Encapsulates complex data structures and algorithms CSC 330 OO Software Design 1 We ve emphasized the importance of software reuse. Recognizing that many data structures and algorithms
More informationCS2255 HOMEWORK #1 Fall 2012
CS55 HOMEWORK #1 Fall 01 1.What is assigned to the variable a given the statement below with the following assumptions: x = 10, y = 7, and z, a, and b are all int variables. a = x >= y; a. 10 b. 7 c. The
More informationCMSC 341 Lecture 6 STL, Stacks, & Queues. Based on slides by Lupoli, Dixon & Gibson at UMBC
CMSC 341 Lecture 6 STL, Stacks, & Queues Based on slides by Lupoli, Dixon & Gibson at UMBC Templates 2 Common Uses for Templates Some common algorithms that easily lend themselves to templates: Swap what
More information! A data type for which: ! In fact, an ADT may be implemented by various. ! Examples:
Ch. 8: ADTs: Stacks and Queues Abstract Data Type A data type for which: CS 8 Fall Jill Seaman - only the properties of the data and the operations to be performed on the data are specific, - not concerned
More information! An exception is a condition that occurs at execution time and makes normal continuation of the program impossible.
Exceptions! Exceptions are used to signal error or unexpected events that occur while a program is running.! An exception is a condition that occurs at execution time and makes normal continuation of the
More informationEECE.3220: Data Structures Spring 2017
EECE.3220: Data Structures Spring 2017 Lecture 14: Key Questions February 24, 2017 1. Describe the characteristics of an ADT to store a list. 2. What data members would be necessary for a static array-based
More informationCS2141 Software Development using C/C++ C++ Basics
CS2141 Software Development using C/C++ C++ Basics Integers Basic Types Can be short, long, or just plain int C++ does not define the size of them other than short
More information(8 1) Container Classes & Class Templates D & D Chapter 18. Instructor - Andrew S. O Fallon CptS 122 (October 8, 2018) Washington State University
(8 1) Container Classes & Class Templates D & D Chapter 18 Instructor - Andrew S. O Fallon CptS 122 (October 8, 2018) Washington State University Key Concepts Class and block scope Access and utility functions
More informationCSC212. Data Structure. Lecture 4 Container Classes. Instructor: George Wolberg Department of Computer Science City College of New York
CSC212 Data Structure Lecture 4 Container Classes Instructor: George Wolberg Department of Computer Science City College of New York 1 Outline Bag class definition/implementation details Inline functions
More informationuse static size for this buffer
Software Design (C++) 4. Templates and standard library (STL) Juha Vihavainen University of Helsinki Overview Introduction to templates (generics) std::vector again templates: specialization by code generation
More informationCOEN244: Class & function templates
COEN244: Class & function templates Aishy Amer Electrical & Computer Engineering Templates Function Templates Class Templates Outline Templates and inheritance Introduction to C++ Standard Template Library
More informationUnit 4 Basic Collections
Unit 4 Basic Collections General Concepts Templates Exceptions Iterators Collection (or Container) Classes Vectors (or Arrays) Sets Lists Maps or Tables C++ Standard Template Library (STL Overview A program
More informationTutorial 12 Craps Game Application: Introducing Random Number Generation and Enumerations
Tutorial 12 Craps Game Application: Introducing Random Number Generation and Enumerations Outline 12.1 Test-Driving the Craps Game Application 12.2 Random Number Generation 12.3 Using an enum in the Craps
More informationComputational Physics
Computational Physics numerical methods with C++ (and UNIX) 2018-19 Fernando Barao Instituto Superior Tecnico, Dep. Fisica email: fernando.barao@tecnico.ulisboa.pt Computational Physics 2018-19 (Phys Dep
More informationLecture-5. STL Containers & Iterators
Lecture-5 STL Containers & Iterators Containers as a form of Aggregation Fixed aggregation An object is composed of a fixed set of component objects Variable aggregation An object is composed of a variable
More informationCS197c: Programming in C++
CS197c: Programming in C++ Lecture 2 Marc Cartright http://ciir.cs.umass.edu/~irmarc/cs197c/index.html Administration HW1 will be up this afternoon Written assignment Due in class next week See website
More informationPreface... (vii) CHAPTER 1 INTRODUCTION TO COMPUTERS
Contents Preface... (vii) CHAPTER 1 INTRODUCTION TO COMPUTERS 1.1. INTRODUCTION TO COMPUTERS... 1 1.2. HISTORY OF C & C++... 3 1.3. DESIGN, DEVELOPMENT AND EXECUTION OF A PROGRAM... 3 1.4 TESTING OF PROGRAMS...
More informationAbstract Data Types (ADTs) 1. Legal Values. Client Code for Rational ADT. ADT Design. CS 247: Software Engineering Principles
Abstract Data Types (ADTs) CS 247: Software Engineering Principles ADT Design An abstract data type (ADT) is a user-defined type that bundles together: the range of values that variables of that type can
More informationCSCI-1200 Data Structures Fall 2017 Lecture 9 Iterators & STL Lists
Review from Lecture 8 CSCI-1200 Data Structures Fall 2017 Lecture 9 Iterators & STL Lists Designing our own container classes Dynamically allocated memory in classes Copy constructors, assignment operators,
More informationDue Date: See Blackboard
Source File: ~/2315/45/lab45.(C CPP cpp c++ cc cxx cp) Input: under control of main function Output: under control of main function Value: 4 Integer data is usually represented in a single word on a computer.
More information1. The term STL stands for?
1. The term STL stands for? a) Simple Template Library b) Static Template Library c) Single Type Based Library d) Standard Template Library Answer : d 2. Which of the following statements regarding the
More informationCE221 Programming in C++ Part 1 Introduction
CE221 Programming in C++ Part 1 Introduction 06/10/2017 CE221 Part 1 1 Module Schedule There are two lectures (Monday 13.00-13.50 and Tuesday 11.00-11.50) each week in the autumn term, and a 2-hour lab
More informationClass and Function Templates
Class and Function 1 Motivation for One Way to Look at... Example: Queue of some type Foo C++ What can a parameter be used for? Instantiating a Template Usage of Compiler view of templates... Implementing
More informationMotivation for Templates. Class and Function Templates. One Way to Look at Templates...
Class and Function 1 Motivation for 2 Motivation for One Way to Look at... Example: Queue of some type Foo C++ What can a parameter be used for? Instantiating a Template Usage of Compiler view of templates...
More informationChapter 5. The Standard Template Library.
Object-oriented programming B, Lecture 11e. 1 Chapter 5. The Standard Template Library. 5.1. Overview of main STL components. The Standard Template Library (STL) has been developed by Alexander Stepanov,
More informationIntroduction to C++ Systems Programming
Introduction to C++ Systems Programming Introduction to C++ Syntax differences between C and C++ A Simple C++ Example C++ Input/Output C++ Libraries C++ Header Files Another Simple C++ Example Inline Functions
More informationLecture 7. Log into Linux New documents posted to course webpage
Lecture 7 Log into Linux New documents posted to course webpage Coding style guideline; part of project grade is following this Homework 4, due on Monday; this is a written assignment Project 1, due next
More informationHeaps. A complete binary tree can be easily stored in an array - place the root in position 1 (for convenience)
Binary heap data structure Heaps A binary heap is a special kind of binary tree - has a restricted structure (must be complete) - has an ordering property (parent value is smaller than child values) Used
More informationSTL Standard Template Library
STL Standard Template Library September 22, 2016 CMPE 250 STL Standard Template Library September 22, 2016 1 / 25 STL Standard Template Library Collections of useful classes for common data structures
More informationCMSC 341 Lecture 6 Templates, Stacks & Queues. Based on slides by Shawn Lupoli & Katherine Gibson at UMBC
CMSC 341 Lecture 6 Templates, Stacks & Queues Based on slides by Shawn Lupoli & Katherine Gibson at UMBC Today s Topics Data types in C++ Overloading functions Templates How to implement them Possible
More informationCSE030 Fall 2012 Final Exam Friday, December 14, PM
CSE030 Fall 2012 Final Exam Friday, December 14, 2012 3-6PM Write your name here and at the top of each page! Name: Select your lab session: Tuesdays Thursdays Paper. If you have any questions or need
More informationCS201 - Introduction to Programming Glossary By
CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with
More informationMotivation for Templates
Motivation for You want both: a list of Location objects a list of MazeMonster objects 1 How can you accomplish this by writing one LinkedList class? state all the ways you can think of doing this state
More informationReview for Test 1 (Chapter 1-5)
Review for Test 1 (Chapter 1-5) 1. Software development 1. Pre-conditions and Post-conditions 2. Running time analysis Big O Timing loops and nested loops 1) Write the simplest big-o expression to describe
More informationCS 247: Software Engineering Principles. ADT Design
CS 247: Software Engineering Principles ADT Design Readings: Eckel, Vol. 1 Ch. 7 Function Overloading & Default Arguments Ch. 12 Operator Overloading U Waterloo CS247 (Spring 2017) p.1/17 Abstract Data
More informationCSCI-1200 Data Structures Fall 2014 Lecture 8 Iterators
Review from Lecture 7 CSCI-1200 Data Structures Fall 2014 Lecture 8 Iterators Designing our own container classes Dynamically allocated memory in classes Copy constructors, assignment operators, and destructors
More informationReview Questions for Final Exam KEY
CS 102 / ECE 206 Spring 11 Review Questions for Final Exam KEY The following review questions are similar to the kinds of questions you will be expected to answer on the Final Exam, which will cover LCR,
More informationAN OVERVIEW OF C++ 1
AN OVERVIEW OF C++ 1 OBJECTIVES Introduction What is object-oriented programming? Two versions of C++ C++ console I/O C++ comments Classes: A first look Some differences between C and C++ Introducing function
More informationLab 2: ADT Design & Implementation
Lab 2: ADT Design & Implementation By Dr. Yingwu Zhu, Seattle University 1. Goals In this lab, you are required to use a dynamic array to design and implement an ADT SortedList that maintains a sorted
More informationCSCI-1200 Data Structures Fall 2010 Lecture 8 Iterators
CSCI-1200 Data Structures Fall 2010 Lecture 8 Iterators Review from Lecture 7 Designing our own container classes Dynamically allocated memory in classes Copy constructors, assignment operators, and destructors
More informationCSI33 Data Structures
Outline Department of Mathematics and Computer Science Bronx Community College November 22, 2017 Outline Outline 1 Chapter 12: C++ Templates Outline Chapter 12: C++ Templates 1 Chapter 12: C++ Templates
More information! Operators such as =, +, <, can be defined to. ! The function names are operator followed by the. ! Otherwise they are like normal member functions:
Operator Overloading, Lists and Templates Week 6 Gaddis: 14.5, 16.2-16.4 CS 5301 Spring 2016 Jill Seaman Operator Overloading! Operators such as =, +,
More informationC++ Programming. Classes, Constructors, Operator overloading (Continued) M1 Math Michail Lampis
C++ Programming Classes, Constructors, Operator overloading (Continued) M1 Math Michail Lampis michail.lampis@dauphine.fr Classes These (and the previous) slides demonstrate a number of C++ features related
More informationEE 355 Unit 10. C++ STL - Vectors and Deques. Mark Redekopp
1 EE 355 Unit 10 C++ STL - Vectors and Deques Mark Redekopp 2 Templates We ve built a list to store integers But what if we want a list of double s or char s or other objects We would have to define the
More informationWhen we program, we have to deal with errors. Our most basic aim is correctness, but we must
Chapter 5 Errors When we program, we have to deal with errors. Our most basic aim is correctness, but we must deal with incomplete problem specifications, incomplete programs, and our own errors. When
More informationDynamic Data Structures
Dynamic Data Structures We have seen that the STL containers vector, deque, list, set and map can grow and shrink dynamically. We now examine how some of these containers can be implemented in C++. To
More informationShort Notes of CS201
#includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system
More informationPIC10B/1 Winter 2014 Exam I Study Guide
PIC10B/1 Winter 2014 Exam I Study Guide Suggested Study Order: 1. Lecture Notes (Lectures 1-8 inclusive) 2. Examples/Homework 3. Textbook The midterm will test 1. Your ability to read a program and understand
More informationDue Date: See Blackboard
Source File: ~/2315/11/lab11.(C CPP cpp c++ cc cxx cp) Input: Under control of main function Output: Under control of main function Value: 1 The purpose of this assignment is to become more familiar with
More informationUEE1302 (1102) F10: Introduction to Computers and Programming
Computational Intelligence on Automation Lab @ NCTU Learning Objectives UEE1302 (1102) F10: Introduction to Computers and Programming Programming Lecture 00 Programming by Example Introduction to C++ Origins,
More informationList, Stack, and Queues
List, Stack, and Queues R. J. Renka Department of Computer Science & Engineering University of North Texas 02/24/2010 3.1 Abstract Data Type An Abstract Data Type (ADT) is a set of objects with a set of
More informationIntroducing C++ to Java Programmers
Introducing C++ to Java Programmers by Kip Irvine updated 2/27/2003 1 Philosophy of C++ Bjarne Stroustrup invented C++ in the early 1980's at Bell Laboratories First called "C with classes" Design Goals:
More informationA linear structure is an ordered (e.g., sequenced) arrangement of elements.
Lists, Stacks, and Queues 1 A linear structure is an ordered (e.g., sequenced) arrangement of elements. There are three common types of linear structures: list stack queue random insertion and deletion
More informationIntroduction to C++ Introduction to C++ 1
1 What Is C++? (Mostly) an extension of C to include: Classes Templates Inheritance and Multiple Inheritance Function and Operator Overloading New (and better) Standard Library References and Reference
More information! Search: find a given target item in an array, ! Linear Search: Very simple search method: ! Operators such as =, +, <, and others can be
Operator Overloading and Templates Week 6 Gaddis: 8.1, 14.5, 16.2-16.4 CS 5301 Spring 2015 Jill Seaman Linear Search! Search: find a given target item in an array, return the index of the item, or -1 if
More informationThe Standard Template Library. An introduction
1 The Standard Template Library An introduction 2 Standard Template Library (STL) Objective: Reuse common code Common constructs: Generic containers and algorithms STL Part of the C++ Standard Library
More informationLesson 13 - Vectors Dynamic Data Storage
Lesson 13 - Vectors Dynamic Data Storage Summary In this lesson we introduce the Standard Template Library by demonstrating the use of Vectors to provide dynamic storage of data elements. New Concepts
More informationInteger Data Types. Data Type. Data Types. int, short int, long int
Data Types Variables are classified according to their data type. The data type determines the kind of information that may be stored in the variable. A data type is a set of values. Generally two main
More informationl Operators such as =, +, <, can be defined to l The function names are operator followed by the l Otherwise they are like normal member functions:
Operator Overloading & Templates Week 6 Gaddis: 14.5, 16.2-16.4 CS 5301 Spring 2018 Jill Seaman Operator Overloading l Operators such as =, +,
More informationMultiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)
Name Closed notes, book and neighbor. If you have any questions ask them. Notes: Segment of code necessary C++ statements to perform the action described not a complete program Program a complete C++ program
More informationCh 4 Pointers and Dynamic Arrays
Ch 4 Pointers and Dynamic Arrays Pointers and Dynamic Memory Pointers and Arrays as Parameters The Bag Class with a Dynamic Array Prescription for a Dynamic Class Programming Project: The String Class
More informationIntroduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts
Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter
More informationCPSC 427a: Object-Oriented Programming
CPSC 427a: Object-Oriented Programming Michael J. Fischer Lecture 17 November 1, 2011 CPSC 427a, Lecture 17 1/21 CPSC 427a, Lecture 17 2/21 CPSC 427a, Lecture 17 3/21 A bit of history C++ standardization.
More informationC++ Functions. Last Week. Areas for Discussion. Program Structure. Last Week Introduction to Functions Program Structure and Functions
Areas for Discussion C++ Functions Joseph Spring School of Computer Science Operating Systems and Computer Networks Lecture Functions 1 Last Week Introduction to Functions Program Structure and Functions
More informationLecture 8. Xiaoguang Wang. February 13th, 2014 STAT 598W. (STAT 598W) Lecture 8 1 / 47
Lecture 8 Xiaoguang Wang STAT 598W February 13th, 2014 (STAT 598W) Lecture 8 1 / 47 Outline 1 Introduction: C++ 2 Containers 3 Classes (STAT 598W) Lecture 8 2 / 47 Outline 1 Introduction: C++ 2 Containers
More informationArrays and Linked Lists
Arrays and Linked Lists Abstract Data Types Stacks Queues Priority Queues and Deques John Edgar 2 And Stacks Reverse Polish Notation (RPN) Also known as postfix notation A mathematical notation Where every
More informationLectures 4 & 5 Container Classes
CSC212 Data Structure - Section FG Lectures 4 & 5 Container Classes Instructor: Feng HU Department of Computer Science City College of New York 1 Container Classes A container class is a data type that
More informationTHE STANDARD TEMPLATE LIBRARY (STL) Week 6 BITE 1513 Computer Game Programming
THE STANDARD TEMPLATE LIBRARY (STL) Week 6 BITE 1513 Computer Game Programming What the heck is STL???? Another hard to understand and lazy to implement stuff? Standard Template Library The standard template
More informationGovernment Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING
Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING THROUGH C++ Practical: OOPS THROUGH C++ Subject Code: 1618407 PROGRAM NO.1 Programming exercise on executing a Basic C++
More informationCOP4530 Data Structures, Algorithms and Generic Programming Recitation 4 Date: September 14/18-, 2008
COP4530 Data Structures, Algorithms and Generic Programming Recitation 4 Date: September 14/18-, 2008 Lab topic: 1) Take Quiz 4 2) Discussion on Assignment 2 Discussion on Assignment 2. Your task is to
More informationFirst Examination. CS 225 Data Structures and Software Principles Spring p-9p, Tuesday, February 19
Department of Computer Science First Examination CS 225 Data Structures and Software Principles Spring 2008 7p-9p, Tuesday, February 19 Name: NetID: Lab Section (Day/Time): This is a closed book and closed
More informationTemplates and Vectors
Templates and Vectors 1 Generic Programming function templates class templates 2 the STL vector class a vector of strings enumerating elements with an iterator inserting and erasing 3 Writing our own vector
More informationChapter 18 - C++ Operator Overloading
Chapter 18 - C++ Operator Overloading Outline 18.1 Introduction 18.2 Fundamentals of Operator Overloading 18.3 Restrictions on Operator Overloading 18.4 Operator Functions as Class Members vs. as friend
More informationCS 216 Exam 1 Fall SOLUTION
CS 216 Exam 1 Fall 2004 - SOLUTION Name: Lab Section: Email Address: Student ID # This exam is closed note, closed book. You will have an hour and fifty minutes total to complete the exam. You may NOT
More informationADTs & Classes. An introduction
ADTs & Classes An introduction Quick review of OOP Object: combination of: data structures (describe object attributes) functions (describe object behaviors) Class: C++ mechanism used to represent an object
More information19.1 The Standard Template Library
Chapter 19: The Template Library From a review of Effective STL : 50 Specific Ways to Improve Your Use of the Standard Template Library by ScottMeyers: It s hard to overestimate the importance of the Standard
More informationOperator Overloading and Templates. Linear Search. Linear Search in C++ second attempt. Linear Search in C++ first attempt
Operator Overloading and Templates Week 6 Gaddis: 8.1, 14.5, 16.2-16.4 CS 5301 Fall 2015 Jill Seaman Linear Search! Search: find a given target item in an array, return the index of the item, or -1 if
More informationProgramming Abstractions
Programming Abstractions C S 1 0 6 B Cynthia Lee Topics du Jour: Make your own classes! (cont.) Last time we did a BankAccount class (pretty basic) This time we will do something more like the classes
More informationCSE 333. Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington
CSE 333 Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington Administrivia New exercise posted yesterday afternoon, due Monday morning - Read a directory
More informationExample Final Questions Instructions
Example Final Questions Instructions This exam paper contains a set of sample final exam questions. It is for practice purposes only. You ll most likely need longer than three hours to answer all the questions.
More informationContainer Class and Integrators, Proxy Class EC6301-OOPS AND DATA STRUCTURES
Container Class and Integrators, Proxy Class Container Class A container class is a data type that is capable of holding a collection of items. A container stores many entities and provide sequential or
More information1 Short Answer (7 Points Each)
1 Short Answer (7 Points Each) 1. Given the following function, what operations will need to be overloaded in the class T for this code to compile? template T square(t n) { return n * n; } The
More informationDATA STRUCTURES AND ALGORITHMS LECTURE 08 QUEUES IMRAN IHSAN ASSISTANT PROFESSOR AIR UNIVERSITY, ISLAMABAD
DATA STRUCTURES AND ALGORITHMS LECTURE 08 S IMRAN IHSAN ASSISTANT PROFESSOR AIR UNIVERSITY, ISLAMABAD S ABSTRACT DATA TYPE An Abstract Queue (Queue ADT) is an abstract data type that emphasizes specific
More information2 ADT Programming User-defined abstract data types
Preview 2 ADT Programming User-defined abstract data types user-defined data types in C++: classes constructors and destructors const accessor functions, and inline functions special initialization construct
More informationDue Date: See Blackboard
Source File: ~/2305/lab06.(C CPP cpp c++ cc cxx cp) Input: Under control of main function Output: Under control of main function Value: 2 Extend the IntegerSet class from Lab 04 to provide the following
More informationUniversity of Illinois at Urbana-Champaign Department of Computer Science. First Examination
University of Illinois at Urbana-Champaign Department of Computer Science First Examination CS 225 Data Structures and Software Principles Spring 2007 7p-9p, Thursday, March 1 Name: NetID: Lab Section
More information