560 likes | 581 Views
Erasmus Exchange in Aristotel University 16-19 april 201 9. Implementing parts of computer systems using Standard Library. Doru Anastasiu Popescu, associate professor, PhD Faculty of Sciences, Physical Education and Informatics Department of Mathematics and Informatics. Standard Library.
E N D
Erasmus Exchange in Aristotel University 16-19 april 2019
Implementing parts of computer systems using Standard Library • Doru Anastasiu Popescu, associate professor, PhD • Faculty of Sciences, Physical Education and Informatics • Department of Mathematics and Informatics
Standard Library Building Offline Application Standard Library Implementation: C++, Java, … classes, objects vector, queue, stack, set, …
Standard Library Building Online Application (Web application) Standard PHP Library (SPL), Standard built-in objects (JavaScript) Cod Source: PHP, JavaScript, … classes, objects
Standard Template Library in C++ • The Standard Template Library (STL) is a software library for the C++ programming language that influenced many parts of the C++ Standard Library. The most important components are containers, iterators and algorithms. • The STL provides a ready-made set of common classes for C++, such as containers and associative arrays, that can be used with any built-in type and with any user-defined type that supports some elementary operations (such as copying and assignment).
Standard Template Library • STL algorithms are independent of containers, which significantly reduces the complexity of the library. • The STL achieves its results through the use of templates. This approach provides compile-time polymorphism that is often more efficient than traditional run-time polymorphism. Modern C++ compilers are tuned to minimize any abstraction penalty arising from heavy use of the STL.
Standard Template Library • The STL was created as the first library of generic algorithms and data structures for C++, with four ideas in mind: generic programming, abstractness without loss of efficiency, the Von Neumann computation model, and value semantics.
Containers • The STL contains sequence containers and associative containers. The standard sequence containers include vector, deque, and list. The standard associative containers are set, multiset, map, multimap, hash_set, hash_map, hash_multiset and hash_multimap. There are also container adaptors queue, priority_queue, and stack, that are containers with specific interface, using other containers as implementation.
pair • The pair container is a simple associative container consisting of a 2-tuple of data elements or objects, called 'first' and 'second', in that fixed order. The STL 'pair' can be assigned, copied and compared. The array of objects allocated in a map are of type 'pair' by default, where all the 'first' elements act as the unique keys, each associated with their 'second' value objects
vector • a dynamic array, like C array (i.e., capable of random access) with the ability to resize itself automatically when inserting or erasing an object. Inserting an element to the back of the vector at the end takes amortized constant time. Removing the last element takes only constant time, because no resizing happens. Inserting and erasing at the beginning or in the middle is linear in time. A specialization for type bool exists, which optimizes for space by storing bool values as bits.
list • a double linked list; elements are not stored in contiguous memory. Opposite performance from a vector. Slow lookup and access (linear time), but once a position has been found, quick insertion and deletion (constant time).
set • Sets are containers that store unique elements following a specific order.In a set, the value of an element also identifies it (the value is itself the key, of type T), and each value must be unique. The value of the elements in a set cannot be modified once in the container (the elements are always const), but they can be inserted or removed from the container.
set • Internally, the elements in a set are always sorted following a specific strict weak ordering criterion indicated by its internal comparison object (of type Compare).set containers are generally slower than unordered_set containers to access individual elements by their key, but they allow the direct iteration on subsets based on their order.
set Sets are typically implemented as binary search trees Methods: • empty, size, clear, insert, erase, swap, count, find, key_comp, value_comp, …
deque • a vector with insertion/erase at the beginning or end in amortized constant time, however lacking some guarantees on iterator validity after altering the deque.
stack • Provides LIFO stack interface in terms of push/pop/top operations (the last inserted element is on top). Any sequence supporting operations back(), push_back(), and pop_back() can be used to instantiate stack (e.g. vector, list, and deque). • #include <stack> • stack<T> s; • T = data type
Stack. Main methods Element access • topaccesses the top element Capacity • emptychecks whether the underlying container is empty • sizereturns the number of elements Modifiers • pushinserts element at the top • popremoves the top element • swapswaps the contents Operators • ==,!=,<,<=,>,>=lexicographically compares the values in the stack
queue • Provides FIFO queue interface in terms of push/pop/front/back operations. • Any sequence supporting operations front(), back(), push_back(), and pop_front() can be used to instantiate queue (e.g. list and deque). • #include<queue> • queue<T> q; • T = data type
queue. Main methods Element access • frontaccess the first element • backaccess the last element Capacity • emptychecks whether the underlying container is empty • sizereturns the number of elements Modifiers • pushinserts element at the end • popremoves the first element • swapswaps the contents Operators • ==,!=,<,<=,>,>=lexicographically compares the values in the queue
priority_queue • Provides priority queue interface in terms of push/pop/top operations (the element with the highest priority is on top). Any random-access sequence supporting operations front(), push_back(), and pop_back() can be used to instantiate priority_queue (e.g. vector and deque). It is implemented using a heap. Elements should additionally support comparison (to determine which element has a higher priority and should be popped first). • #include <queue> • priority_queue<T> p; • T=data type
priority_queue Element access • Topaccesses the top element Capacity • emptychecks whether the underlying container is empty • sizereturns the number of elements Modifiers • pushinserts element and sorts the underlying container • popremoves the top element • swapswaps the contents Operators • ==,!=,<,<=,>,>=lexicographically compares the values in the priority_queue
Applications Stacks Let n, m - natural numbers with a maximum of 5 digits, m≤n. Write a C ++ program to solve the requirements: • Build a stack s with numbers 1, 2, ..., n. Copy the stack in t. Display stack s. • Delete components from stack t. Display the number of stack components t. • Display stack t. Example n= 10 m=6 • 10 9 8 7 6 5 4 3 2 1 • 4 • 4 3 2 1
C++ program Stacks #include <iostream> #include <stack> using namespace std; int main() { stack<int> s, t; int n,m,i; cout<<"n=";cin>>n; cout<<"m=";cin>>m; cout<<"a) "; for(i=1;i<=n;i++) s.push(i); t=s; while(!s.empty()){ cout<<s.top()<<" "; s.pop(); } cout<<'\n'; for(i=1;i<=m;i++) t.pop(); cout<<"b) "<<t.size()<<'\n';; cout<<"c) "; while(!t.empty()){ cout<<t.top()<<" "; t.pop(); } return 0; }
Applications queue Let n- natural number with a maximum of 5 digits. Write a C ++ program to solve the requirements: • Build queue c with the first n prime numbers. Copy the c queue in t. Display queue c. • Delete n/2 components from the queue t. Display queue t. Example n= 7 • 2 3 5 7 11 13 17 • 7 11 13 17
C++ program queue #include <iostream> #include<queue> using namespace std; int prim(int k){ int i; if(k<2) return 0; for(i=2;i<=k/2;i++) if(k%i==0) return 0; return 1; } int main() { int n,k,nr; queue<int> c,t; cout<<"n=";cin>>n; cout<<"a) "; k=2;nr=0; while(nr<n){ if(prim(k)){ c.push(k); nr++; } k++; } t=c; nr=c.size(); for(k=1;k<=nr;k++){ cout<<c.front()<<" "; c.pop(); } cout<<'\n'; cout<<"b) "; for(k=1;k<=nr/2;k++) t.pop(); while(!t.empty()){ cout<<t.front()<<" "; t.pop(); } return 0; }
Applications priority_queue Let n- natural number with a maximum of 4 digits and n natural numbers. Write a C ++ program to solve the requirements: • Build a priority queue c with the given numbers. Copy the stack in t. Display priority queue c . • Delete n/2 components priority queue t. Display priority queue t. Example 7 88 34 2 56 100 3 14 • 100 88 56 34 14 3 2 • 34 14 3 2
C++ program priority_queue #include <iostream> #include <queue> using namespace std; int main() { priority_queue<int> c,t; int i,n,x,nr; cin>>n; for(i=1;i<=n;i++){ cin>>x; c.push(x); } cout<<"a) "; t=c; nr=c.size(); for(i=1;i<=nr;i++){ cout<<c.top()<<" "; c.pop(); } for(i=1;i<=nr/2;i++) t.pop(); cout<<'\n'; cout<<"b) "; while(!t.empty()){ cout<<t.top()<<" "; t.pop(); } return 0; }
Applications Set, queue • It gives an undirected graph with n vertices and m edges. Visit the node of the graph starting from node r using BFS algorithm (breadth first search). Example
Applications set, queue #include <fstream> #include <queue> #include <set> using namespace std; ifstream fin("graph.in"); ofstream fout("graph.out"); int main() { int n,m,i,j,k,r; //read data fin >> n >> m>> r; // n = number of vertex, m = number of edge, r is start vertex set <int> A[n+1]; bool v[n+1]; // vector for visiting vertex for(i=1;i<=n;i++) v[i]=false;
Applications set, queue for(k=1;k<=m; k++){ //read edge [i,j] fin>>i>>j; A[i].insert(j); A[j].insert(i); } // Q is queue with vertex (nods) queue <int> Q,Q1; Q.push(r);Q1.push(r); v[r]=true; while(!Q.empty()){ k=Q.front(); Q.pop(); for(i=1;i<=n;i++) if(!v[i] && A[k].find(i)!=A[k].end()) { v[i]=true; Q.push(i); Q1.push(i); } } //display vertex from Q1 while(!Q1.empty()){ fout<<Q1.front()<<" "; Q1.pop(); } return 0; }
Proposed problems stack 1. Let n- natural number with a maximum of 4 digits and n natural numbers. Write a C ++ program to solve the requirements: • Build a stack S with the given numbers. Display elements of S. • Display elements of S in order of reading. Example 4 89 4 56 7 • 7 56 4 89 • 89 4 56 7
Proposed problems queue 2. Let n- natural numbers with a maximum of 4 digits and n natural numbers. Write a C ++ program to solve the requirements: • Build a queue T with the given numbers. Display maximum element of T. • Display elements of T in the reverse order of reading. Example 4 9 4 56 7 • 56 • 7 56 4 9
Proposed problems set, queue • It gives an undirected graph with n vertices and m edges. Visit the node of the graph starting from node r using DFS algorithm (Depth First Search). Example
Proposed problems set, stack, queue • It gives an undirected graph with n vertices and m edges. Using the DFS or BFS algorithm find the conex components in the graph. Example
PriorityQueue in Java • Methods in PriorityQueue class: • boolean add(E element): This method inserts the specified element into this priority queue. • public remove(): This method removes a single instance of the specified element from this queue, if it is present • public poll(): This method retrieves and removes the head of this queue, or returns null if this queue is empty.
PriorityQueue in Java • Methods in PriorityQueue class: • public peek(): This method retrieves, but does not remove, the head of this queue, or returns null if this queue is empty. • Iterator iterator(): Returns an iterator over the elements in this queue. • boolean contains(Object o): This method returns true if this queue contains the specified element • void clear(): This method is used to remove all of the contents of the priority queue.
priority_queue Java. Example • Create a priorityqueue with the names of 3 countries (Romania, Greece and Bulgaria), each country will be inserted n times. • a) Show the element at the top of the priorityqueue without wiping it • b) Wipe the first k in the priorityqueue. • c) Delete Romania from the priorityqueue • d) Check if the priorityqueue contains Greece
Java program priority_queue import java.util.*; import java.util.Scanner; class ExamplePriorityQueue { public static void main(String args[]) { // Creating empty priority queue PriorityQueue<String> pQueue = new PriorityQueue<String>(); // Adding items to the pQueue using add() Scanner cin=new Scanner(System.in); int n,x,i,k; n=cin.nextInt(); k=cin.nextInt();
Java program priority_queue for(i=1;i<=n;i++) pQueue.add("Romania"); for(i=1;i<=n;i++) pQueue.add("Greece"); for(i=1;i<=n;i++) pQueue.add("Bulgaria"); // Printing the most priority element System.out.println("Head value using peek function:" + pQueue.peek()); // Printing all elements System.out.println("The queue elements:"); Iterator<String> itr = pQueue.iterator(); while (itr.hasNext()) System.out.println(itr.next());
Java program priority_queue // Removing k top priority elements (or head) and // printing the modified pQueue using poll() for(i=1;i<=k;i++) pQueue.poll(); System.out.println("After removing " +k +" elements " + "with poll function:"); Iterator<String> itr2 = pQueue.iterator(); while (itr2.hasNext()) System.out.println(itr2.next());
Java program priority_queue // Removing using remove() pQueue.remove("Romania"); System.out.println("after removing Romania with" + " remove function:"); Iterator<String> itr3 = pQueue.iterator(); while (itr3.hasNext()) System.out.println(itr3.next()); // Check if an element is present using contains() boolean b = pQueue.contains("Greece"); System.out.println ( "Priority queue contains Greece " + "or not?: " + b); } }
Java priority_queue
JavaScript - Set • Set objects are collections of values. You can iterate through the elements of a set in insertion order. A value in the Set may only occur once; it is unique in the Set's collection. • new Set([iterable]); => If an iterable object is passed, all of its elements will be added to the new Set. If you don't specify this parameter, or its value is null, the new Set is empty. • Properties: size
JavaScript – Set Method add(value) - Appends a new element with the given value to the Set object. Returns the Set object clear() - Removes all elements from the Set object. delete(value) - Removes the element associated to the value and returns the value that has(value) - Returns a boolean asserting whether an element is present with the given value in the Setobject or not. …
JavaScript.Example • Let n be a natural number. Enter name of countries until there are n distinct name of countries. • Build a set with the names of the countries and display it. Example Input n=3 Romania Greece Greece Bulgaria Output Romania Greece Bulgaria
Script <html> <head> <script type="text/javascript"> s = new Set(); n=parseInt(prompt("Input a natural number n=")); alert("Input country names until they are n distinct countries"); do{ a=prompt("Input the name of a country"); s.add(a); }while(s.size!=n);
alert(" All name of a countrys:"); AllCountries=""; for (let item of s) AllCountries = AllCountries +item + " "; alert(AllCountries); </script> </head> <body> </body> </html>
PHP - array Until version 5, the most commonly used object was array. It allowed operations such as deleting, inserting, sorting, copying, etc. Starting with version 7 in PHP, a powerful library of classes with data structures in STL - C ++ have been introduced. This library is called SPL (Standard PHP Library). Here's an example of an array.
PHP - Example • Let n and k natural numbers. • Build an array with the names of 3 countries (Romania, Greece and Bulgaria), each country will be inserted n times. Then display the array. • Delete k country names and display the array. • Order the name of the countries remaining in the array and display the array.
PHP - Script <?php $n=$_POST['n']; $k=$_POST['k']; $a = array(); $index = 0; for($i=1;$i<=$n;$i++) $a[++$index]="Romania"; for($i=1;$i<=$n;$i++) $a[++$index]="Greece"; for($i=1;$i<=$n;$i++) $a[++$index]="Bulgaria";