1 / 32

C++ Standard Template Library

C++ Standard Template Library. OOPSLA Lab. 교수 김형주. Contents. Fundamental Concept Preliminaries Function Object STL Overview Internal Functioning STL Containers STL Iterators STL Algorithms. Fundamental Concept - A Typical Container Class. A String Class Example.

dareh
Download Presentation

C++ Standard Template Library

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. C++ Standard Template Library OOPSLA Lab. 교수 김형주 OOPSLA Lab. SNU

  2. Contents • Fundamental Concept • Preliminaries • Function Object • STL Overview • Internal Functioning • STL Containers • STL Iterators • STL Algorithms OOPSLA Lab. SNU

  3. Fundamental Concept- A Typical Container Class A String Class Example A Typical Container Class Character Array Structure for holding Data get_at(), insert_at(), ... Data Access Methods copy(), concatenate(), to_uppercase(), … Methods for manipulating/modifying the Data (Algorithms) * String : A container for characters OOPSLA Lab. SNU

  4. Fundamental Concept- Problems without STL(1) • Most Containers have common algorithms • copy, find, sort, merge … • Problems • n different containers (list, set, stack, queue, …) • m possible data types (int, char, user-defined, …) • k necessary algorithms (copy, find, sort, …) • must write n*m*kalgorithms • using template : reduce m to 1 n*k OOPSLA Lab. SNU

  5. Fundamental Concept- Problems without STL(2) Containers … Queue List Set … Float Set int Set n Containersm Data Typesk Algorithms … … Find Find n*m*k implementations OOPSLA Lab. SNU

  6. Fundamental Concept- generic component (STL) • Write the common algorithms once !! • Make all containers provide same generic data access methods (that is an iterator) Reduce n*m*k implementations to n+k OOPSLA Lab. SNU

  7. Preliminaries- operator overloading • To overload an operator op • make a method which can do the operation • rename the method to operator op(…) class String{private: char contents[1024];public: String(char *s){ strcpy(contents, s);}; String operator +(String& s){ char buf[1024]; strcpy(buf, contents); strcat(buf, s.contents); return String(buf); }}; int main(){ String s1, s2, s3; ……….. s3 = s1+s2; …………..; …………..;} OOPSLA Lab. SNU

  8. Preliminaries- template • Write one class for various data types • Use template<class type_variable> template <class T>class Stack{private: T the_stack[1024]; int top;public: Stack(){ top = -1; }; void Push(T& item) { the_stack[++top] = item);T& Pop() { return the_stack[top--];}}; int main(){Stack<int> int_stack; ………; int_stack.push(1); int item = int_stack_pop(); ……….;} OOPSLA Lab. SNU

  9. Function Object • Function Object (Functor) • Algorithmic object • Take the place of the function pointer in C • Work by overloading operator () template < class T >struct square { T operator()(T n) {return n*n;} };template < class T, class funcObj > void printEval(T val,funcObj f) { cout << f(val) << endl; }; main() { printEval(1.4, square < float > ()); printEval(1.4, square < int > ()); return 0;} OOPSLA Lab. SNU

  10. STL Overview A Generic Container Class A Typical Container Class Structure for holding Data Structure for holding Data Data Access Methods Data Access Methods(iterator class) Methods for manipulating/modifying the Data (Algorithms) Algorithms OOPSLA Lab. SNU

  11. Internal Functioning- generic find algorithm template<class IteratorType, class T> IteratorType find(IteratorType begin, IteratorType end, const T& Value) { while(begin != end && *begin != Value) ++begin; return begin; } OOPSLA Lab. SNU

  12. Internal Functioning- slist class (a container) template<class T>class slist{ public: slist() : firstElement(0), Count(0) {} void push_front(const T& Datum){ Element *temp = new Element(Datum,firstElement); firstElement = temp; ++Count; } private: struct Element{ T Data; Element *Next; Element(const T& Datum, Element *p) : Data(Datum), Next(p) {} }; Element *firstElement; size_t Count; public:class iterator{ public: iterator(Element* Init=0) : current(Init){} T& operator*(){ return current->Data; } iterator& operator++(){} // prefix iterator operator++(int){}// postfix int operator-(iterator fromWhere){} bool operator==(const iterator& x) const {} bool operator!=(const iterator& x) const {} private: Element* current; };// iterator iterator begin() {return iterator(firstElement);} iterator end() {return iterator();}}; // end of slist OOPSLA Lab. SNU

  13. Internal Functioning- main function int main(){ slist<int> aContainer; int number; for(int i = 100; i >=0; i--) aContainer.push_front(2*i); cin >> number; slist<int>::iterator Position = find(aContainer.begin(), aContainer.end(), number); if(Position != aContainer.end()) cout << “Found at ” << (Position - aContainer.begin()); else cout << number << “ not found!” << endl;} OOPSLA Lab. SNU

  14. STL Containers- overall structure STL Containers Associative Sequence Sequence map deque vector list set 1 2 3 4 multimap multiset 1 1 2 2 OOPSLA Lab. SNU

  15. STL Containers- sequence • Vector • Fast insertion at end, and allow random access • List • Fast insertion anywhere, but provide only sequential access • Deque • Fast insertion at either end, and allow random access OOPSLA Lab. SNU

  16. STL Containers- associative sequence • Set • allow you to add and delete elements, query for membership, and iterate through the set • Multiset • just like sets, except that you can have several copies of the same element (often called bags) • Map • mapping from one type (key) to another type (value) • Multimap • a key can be associated with several values OOPSLA Lab. SNU

  17. STL Containers- example : vector struct Entry{ string name; int number; } vector<Entry> phone_book(1000); void print_entry(int i) // exactly as for array { cout << phone_book[i].name << ‘ ‘ << phone_book[i].number; } void add_entries(int n) // increase size by n { phone_book.resize(phone_book.size() + n); } OOPSLA Lab. SNU

  18. STL Containers- example : list(1) #include <string> #include <list> list<string> student; void main() { list<string>::iterator i; // declare iterator student.push_ front(“A”); student.push_back(“B”); student.push_ front(“C”); i = student.begin(); i++; student.insert(I, “D”); for (list<string>::iterator j = student.begin(); j != student.end(); ++j){ string s = *j; cout << "student's name is :" << s << ''; } } OOPSLA Lab. SNU

  19. STL Containers- example : list(2) • student.push_ front(“C”); student C A B • student.insert(i, “D”); iterator i student A B C D OOPSLA Lab. SNU

  20. STL Containers- example : map #include <string> #include <map> void main() { map<int, string> student; student[502] = ”Jane"; student[505] = ”Jone"; cout << "ID 502 : name is " << student[502] << endl; cout << "ID 505 : name is " << student[506] << endl; } OOPSLA Lab. SNU

  21. STL Iterators(1) • Iterator • an abstract of the notion of a pointer to an element of a sequence • key concept is • the element currently pointed to ( operator * and -> ) • point to next element ( operator ++ ) • equality ( operator == ) • The standard algorithm find looks for a value in a sequence and returns an iterator to the element found OOPSLA Lab. SNU

  22. STL Iterators(2) A Container Container v 2 1 4 5 3 0 iter v.push_front(value) *iter = value Algorithms OOPSLA Lab. SNU

  23. begin() end() M a n y s t u d e n t u s e i n t e r n e t STL Iterators(3) #include<string> #include<algorithm> void main() { string s = "Many students use internet"; string::iterator i = find(s.begin(), s.end(), 'e'); int n = 0; while ( i != s.end()) { ++n; i = find(i+1, s.end(), 'e'); } cout << "The number of e : " << n << endl; } OOPSLA Lab. SNU

  24. STL Iterator types- overview • Iterator types can be as different as the containers and the specialized needs they serve Input Forward Bidirectional Random access Output OOPSLA Lab. SNU

  25. STL Iterator types- input iterators • Designed for reading a sequential stream of input data (c.f. istream) • No write access to the object is possible(dereferencing does not supply an lvalue) SourceIterator = Stream_Container.begin();while(SourceIterator != Stream_Container.end()){ Value = *SourceIterator; ++SourceIterator;} 2 1 4 5 3 0 OOPSLA Lab. SNU

  26. STL Iterator types- output iterators • Designed for writing into both a container and the sequential stream of output data (c.f. ostream) • No read access to the object is possible DestinationIterator = Stream_Container.begin();while(DestinationIterator != Stream_Container.end()){ *DestinationIterator = Value; ++DestinationIterator;} 2 1 4 5 3 0 OOPSLA Lab. SNU

  27. STL Iterator types- forward iterators • Both reading and writing is possible • Move only forward by one • Overloading the operator++ 2 1 4 5 3 0 OOPSLA Lab. SNU

  28. STL Iterator types- bidirectional iterators • Both reading and writing is possible • Move forward and backward by one • Overloading the operator++ & operator-- 2 1 4 5 3 0 OOPSLA Lab. SNU

  29. STL Iterator types- random acess iterators • Both reading and writing is possible • Move anywhere like an array index • Overloading the operator[] 2 1 4 5 3 0 OOPSLA Lab. SNU

  30. Generic Algorithms(1) • Many algorithms share a common basic behavior and a common interface style • The standard library provides the most common algorithms for containers • Each algorithm is expressed as a template function • For_each template<class In, class UnaryFunction> UnaryFunction for_each (In first, In last, UnaryFunction f) { while (first != last) f(*first++); return f; } OOPSLA Lab. SNU

  31. Generic Algorithms(2) #include <vector> #include <string> #include <algorithm> vector<string> student(3); void main() { student[0] = “winter"; student[1] = “spring”; student[2] = “hjkpark”; cout << "Before sort : "; cout << student[0] << ' ' << student[1] << ' ' << student[2] << endl; sort(student.begin(),student.end()); cout << "After sort : "; cout << student[0] << ' ' << student[1] << ' ' << student[2] << endl; } OOPSLA Lab. SNU

  32. Generic Algorithms(3) Selected Standard Algorithms for_each( ) Invoke function for each element find( ) Find first occurrence of arguments find_if( ) Find first match of predicate count( ) Count occurrences of element count_if( ) Count matches of predicate replace( ) Replace element with new value replace_if( ) Replace element that matches predicate with new value copy( ) Copy elements unique_copy( ) Copy elements that are not duplicates sort( ) Sort elements equal_range( ) Find all elements with equivalent values merge( ) Merge sorted sequences OOPSLA Lab. SNU

More Related