CSCI 262

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

maps

#include <map> template <class K, class V> class map Method summary: .at(K key) // get value associated with key; throws exception if not found .insert(pair<K,V> entry) // put a key/value pair into map. will not overwrite .emplace(K key, V value) // put a key/value pair into the map. will not overwrite .erase(K key) // remove key/value pair from map .find(K key) // get iterator to entry. returns .end() if none .end() // End iterator .begin() // Begin iterator .count(K key)// count matching entries .size()// number of entries .empty()// true if no entries operator[](K key) // get and put and update (returns a reference to value associated with key; creates default entry if not found). will overwrite

pair

#include <utility>// or <map>, <set>, others template <class A, class B> class pair public member variables (not methods): first // first element second // second element Verbose: pair<type1, type2> p; p.first= obj1; p.second= obj2; Quicker: auto p = make_pair(obj1, obj2); Sneaky quick way, when a pair is expected, e.g. as arg: { obj1, obj2 }

?

(condition) ? true-clause : false-clause

vectors

.begin() // Return iterator to beginning .end() // Return iterator to end .size() // Returns the number of elements in the vector. .empty() // Test whether vector is empty operator[] // Returns a reference to the element at position n in the vector container. .push_back(type); // Add element at the end .pop_back() // Delete last element iterator insert (iterator position, const value_type& val); .insert (iterator position, size_type n, const value_type& val); // Insert elements. The vector is extended by inserting new elements before the element at the specified position, effectively increasing the container size by the number of elements inserted. If n is specified, then it inserts n copies of val .erase (iterator position); .erase (iterator first, iterator last); // Erase elements. Removes from the vector either a single element (position) or a range of elements ([first,last)). .clear() // Removes all elements from the vector (which are destroyed), leaving the container with a size of 0. #include <algorithm> .swap(vector x) // Exchanges the content of the container by the content of x, which is another vector object of the same type. Sizes may differ. std::sort (myvector.begin(), myvector.end()); // Sorts vector it=std::set_difference (first, first.end(), second, second.end(), out.begin()); // Set difference, with extra in out. Note, inputs must be sorted out.resize(it-out.begin()); // Removes extra in out same process with std::set_union and set_intersection

strings

.begin() // Returns an iterator pointing to the first character of the string. .end() // Returns an iterator pointing to the past-the-end character of the string. The past-the-end character is a theoretical character that would follow the last character in the string. It shall not be dereferenced. .size() // Returns the length of the string, in terms of bytes. This is the number of actual bytes that conform the contents of the string, which is not necessarily equal to its storage capacity. .length() //Same as size .empty() // Returns whether the string is empty (i.e. whether its length is 0). operator[] // The character at the specified position in the string. .at(int) // Same as [] .back() // Returns a reference to the last character of the string. .front() // Returns a reference to the first character of the string. operator+= // Extends the string by appending additional characters at the end of its current value: .append(string) //Extends the string by appending additional characters at the end of its current value .push_back(char) // Appends character c to the end of the string, increasing its length by one. .insert(size_t pos, const string& str); // Inserts additional characters into the string right before the character indicated by pos (or p): .erase (size_t pos = 0, size_t len = npos); // Erases the portion of the string value that begins at the character position pos and spans len characters (or until the end of the string, if either the content is too short or if len is string::npos. Notice that the default argument erases all characters in the string (like member function clear). .erase (iterator p); // Erases the character pointed by p. .erase (iterator first, iterator last); // Erases the sequence of characters in the range [first,last). string::npos // npos is a static member constant value with the greatest possible value for an element of type size_t. As a return value, it is usually used to indicate no matches. .replace (size_t pos, size_t len, const string& str); .replace (iterator i1, iterator i2, const string& str); // Replaces the portion of the string that begins at character pos and spans len characters (or the part of the string in the range between [i1,i2)) by new contents: .pop_back() // Erases the last character of the string, effectively reducing its length by one. .find (const string& str, size_t pos = 0) const; // Searches the string for the first occurrence of the sequence specified by its arguments. The position of the first character of the first match. If no matches were found, the function returns string::npos. .substr (size_t pos = 0, size_t len = npos) //Returns a newly constructed string object with its value initialized to a copy of a substring of this object. The substring is the portion of the object that starts at character position pos and spans len characters (or until the end of the string, whichever comes first).

Recursive functions must have

Base case and must reduce problem, otherwise infinite

Analysis

Count number of basic machine tasks, then see if that number is related to 1, log(n), n, nlog(n), n^2, n^3, n^m, 2^n, e^n, m^n, n!, n^n, etc. Note, sum of arithmetic series (0+1+...+n) = (n^2+n)/2, or O(n^2) Things that cut problem in half repeatedly are log

Merge sort

Divide in half, sort each half, merge halves back together. Sort each half by merge sorting. Merge back together by taking the lesser of first remaining element of each list as the next eleemnt. Since a merge happens( O(n)) for each level, and each level halves the problem, its O(nlogn)

queue

FIFO #include <queue> template <class ValueType> class .push(ValueType v) // enqueue (add value to back) .pop() // dequeue (remove front value) .front() // return front value .back() // return back value .size() // return number of elements .empty() // true if no elements

sets

Find (test for presence of) an item in the set Insert an item into the set (preserving uniqueness) Remove an item from the set Types of Sets: Ordered sets: Items must be comparable Items are iterated in sort order Typically implemented using binary search trees Unordered sets: Typically faster than ordered sets Items are iterated in no particular order Implemented using hashtables #include <set> template <class T> class set Methods: .find(T &val) // Find matching element (returns iterator) returns .end() if none found .count(T &val) // Find matching element (returns count) .insert(T &val) // Insert element, if not present. returns iterator to that element .emplace(T &val) // Same as insert .erase(T &val) // Remove element, if present .size() // Return number of elements .empty() // Return true if no elements .begin() // Get iterator to "first" element of set .end() // Get iterator marking "end" of set #include <unordered_set> Same as ordered set, iterable but not in order

Selection sort

Find min element, swap with first. Sort remaining list. O(n^2)

stacks

LIFO (Last in, first out) #include <stack> template <class ValueType> class stack .push(ValueType v) // push value onto top of stack .pop() // pop (remove) top value .top() // return top value .size() // return number of elements .empty() // true if no elements

Operator overloading

Non member: T1 operator+(const T1 &a, const T2 b){ //Things return a type T1 } Member: T1 T1::operator+(const T2 &b) const { // Can use private variables of both, plain for *this or with b.var return type T1 } Assignment must be member function, << and >> must not be member function, for exam, everything that isnt assignment is non-member

iterators

Objects which point to elements of a container In the abstract, work much like pointers Use dereference operator (*) to access value (not always writeable. it is for vectors, not for sets. etc.) Use ++ to advance to next element .end() is typically element past end, dont star it or problems because it doesnt exist. type::iterator it or auto it work set<string> fruit = {"pear", "apple", "orange", "cherry"}; set<string>::iterator iter= fruit.begin(); while (iter!= fruit.end()) { cout<< *iter<< ' '; iter++; }

pointers

Point to a place in memory. int x = 1234; int* p=&x; // p points to x & = reference operator, takes int and gives int* cout << *p << endl; // prints 1234 * = dereference operator, can be used to view or set x *p=5678; // x=5678 C++ defines a special keyword for pointers which do not currently point to anything: nullptr int* p = nullptr; cout << *p << endl; // crash *p = 42; // also crash (*p).foo is the same as p->foo p[i] is the same as *(p+i) void foo(int &x) { ... } Do not use *x, use x. Pointers are used under the covers, and modifies original x. this pointer is only defined in classes and points to current object

Linked lists

Stores value and pointer to next element. Array, Linked add: 1,1(with tail pointer) insert: n,1(with pionter at location) erase: n,1(with pointer at location) indexed get/set: 1,n append: n,1

Hash tables

Thing->hash->index in array/place to look for it Collisions fixed mainly by chaining (aka linked lists at each index in array) Assuming "uniform hashing", find is O(1), insert is O(1), and erase is O(1), because linked lists. Used in unordered maps, sets, expect O(1) for everything.

Binary trees

Traversal: In order: left, root, right Pre: root, left right Post: left, right, root Items in left subtree < item at root < items in right Trees can become unbalanced through inserts and deletes. Some can self balance by O(log(n)) after insert, delete. Hight it kept at O(log(n)) Find: O(log(n)) Insert: find and then insert a new leaf, so O(log(n)) Remove: Trickier if they have a child, otherwise just a find. Used in ordered maps, sets. Expect O(log(n)) for everything.

Inheretance

class animal{ public: string name; void print(); }; class dog : public animal{ public: string breed; void print(); // Can redefine for dog, or if not present takes default from animal } Note: calls superclass default constructor before its own. But can be overridden to call non-default constructor with animal::animal(string nm){name=nm;} dog::dog(string n, string b) : animal(n) { breed=b;} if: class A class B : public A class C : public B B * ptr = new A ; // Not okay, B is more than A, A is not a B, B is a A B * ptr2 = new C ; // Fine, C is a B class animal class dog : public animal class goldenRetriever : public dog dog * ptr = new animal ; // Not okay, dog is more than animal, animal is not a dog, dog is an animal dog * ptr2 = new goldenRetriever ; // Fine, goldenRetriever is a dog

Class def

class student { public: string name; string year; double gpa; bool is_hungry; student(); // Constructor student(const student& stu); // Copy constructor (big 3) student& operator=(const student& stu); // Assignment operator (big 3) ~number(); // Destructor (big 3) void eat(); void sleep(); void program(int); friend dom::func(T vars); //Can access private vars private: int things; }; //Dont forget

Abstract class

contains at elast one pure virtual method, which cannot be instantiated and is only used via inheretance. (non abstract) childred must implement the virtual methods. virtual methods must be public, no friends or statics either class base{ public: virtual void print (){ cout<< "print base class" <<endl; } // not pure virtual, is defined here. pure virtual wouldnt be defined and muse be defined by derivateive, but this is anyway void show (){ cout<< "show base class" <<endl; } }; class derived:public base{ public: void print (){ cout<< "print derived class" <<endl; } void show (){ cout<< "show derived class" <<endl; } }; int main(){ base *bptr; derived d; bptr = &d; bptr->print(); //virtual function, binded at runtime bptr->show(); // Non-virtual function, binded at compile time } prints: print derived class show base class

Templating

function: template<class T> void func(T &a, T &b){ things; } func<double>(1.0,2.1); class: template<class K, class V> class name{ public: K thingy; V otherthingy; ... } name<int, string> (1,"HI");

Dynamic memory allocation

https://cs.mines.edu/Courses/csci262/lectures/L10-Dynamic.pdf The stack: local variables, function arguments, return values. Grows "down". The heap: dynamically allocated memory. Grows "up". Global and static variables, constants. Program code. Read only! The heap: Get pieces of it ("allocate memory") using new Pieces stay allocated until explicitly released by use of delete foo *fp = new foo; double *dp = new double[100]; make sure to delete using delete fp; delete[] dp; Never: Dereference a pointer which has not been set to valid memory (using new or &) Dereference a pointer to memory which has been deallocated (a dangling pointer) Change or lose a pointer which is pointing to dynamically allocated memory (or you won't be able to deallocate - this causes a memory leak) Use delete on a pointer which isn't pointing to dynamically allocated memory (e.g., a dangling or NULL pointer)

For loop :

vector<int> nums = {1,2,3,4}; for(int x : nums){ cout << nums << endl; }


Kaugnay na mga set ng pag-aaral

EMT Chapter 35: Geriatric Emergencies

View Set

At least 100 of these will be on the OB test

View Set

Ch 52 Nursing Management: Patients w/ Dermatologic Problems

View Set