300 likes | 440 Views
Today’s Topic. Standard template library (STL) Introduction Iterators: I/O Sequence containers: vector Associative containers: map Container adapter: stack Algorithms: searching & sorting. Reminders. Final Exam Thursday, December 19 th , 12:00 – 2:00 pm Covers last 1/3 of class
E N D
Today’s Topic • Standard template library (STL) • Introduction • Iterators: I/O • Sequence containers: vector • Associative containers: map • Container adapter: stack • Algorithms: searching & sorting
Reminders • Final Exam • Thursday, December 19th, 12:00 – 2:00 pm • Covers last 1/3 of class • Course grade • Will be posted Friday morning • Exams = 300 points • Assignment = 250 points • Total = 550 points
Introduction • Standard Template Library (STL) • Platform independent class libraries • Three components of STL • Containers • Iterators • Algorithms
Containers • Common data structures written as a template class • Three types • Sequence containers • Associative containers • Container adapters • First class containers • Sequence & associative containers • Have certain member functions that container adapters do not have
Sequence Containers • vector • Rapid insertions & deletions at back • Direct access to any element • deque • Rapid insertions & deletions at front or back • Direct access to any element • list • Doubly-linked list • Rapid insertions & deletions anywhere
Associative Containers • set • Rapid lookup, no duplicates allowed • multiset • Rapid lookup, duplicates allowed • map • One to one mapping, rapid key-based lookup, no duplicates allowed • multimap • One to one mapping, rapid key-based lookup, duplicates allowed
Container Adapters • stack • Last-in-first-out • queue • First-in-first-out • priority_queue • Highest priority element is always the first element out
Member Functions • Common member functions for all STL containers • Default constructor, copy constructor, destructor • Each container has several overloaded constructors • empty() • True if no elements in container; false otherwise • size() • Number of elements in the container • operator= • Assigns one container to another
Member Functions II • operator< • True if 1st container is less than the 2nd container • Otherwise returns false • operator<=, >, >=, ==, != • True if 1st is <=, >, >=, ==, or != 2nd • Otherwise returns false • swap • Swaps the elements of two containers
Header Files <vector> <list> <deque> <queue> (has queue & priority_queue) <stack> <map> (has map & multimap) <set> (has set & multiset) <bitset>
Iterators • Iterators similar to pointers • Used to point to elements of 1st class containers • Operators • Dereferencing operator (*) • Dereferences an iterator, so you can use the element to which it points • Increment operator (++) • Moves the iterator to the next element of the container
Iterators II • Operators • begin() • Points to the 1st element of the container • end() • Points one element past the end of the container • Is used only in an equality or inequity comparisons • Iterator objects • iterator points to an element that can be modified • const_iterator points to a constant element
Example I/O & Iterators #include <iostream> #include <iterator> using std::cout; using std::cin; using std::endl; void main(){ int num1, num2; cout<<"Enter two integers: "; std::istream_iterator<int> input(cin); num1=*input; //read first int from standard input ++input;//move iterator to next input value num2=*input; //read next int from standard input cout<<num1<<" + "<<num2<<" = "; std::ostream_iterator<int> output(cout); *output=num1+num2; //output result to cout cout<<endl; }
std:: • Each STL function & definition needs to be preceded with std:: • Should not use using std::, or using namespace std at top of program • Since the code generated by using STL is complicated, it is difficult to construct the proper using statements
Input Iterators std::istream_iterator<int> input(cin); • Creates an istream_iterator that is capable of extracting (inputting) int values from the standard input object cin num1 = *input; • Dereferences iterator input to read the first integer from cin & assign value to num1 ++input; • Positions iterator input to the next value in the input stream
Output Iterators std::ostream_iterator<int> output(cout); • Creates an ostream_iterator that is capable of inserting (outputting) int values in the standard output object cout *output = num1 + num2; • Outputs an integer to cout by assigning to *output the sum of num1 & num2 • (See ioIterator.txt)
Algorithms • STL provides generic algorithms that can be used in most containers • Around 70 standard algorithms • Example algorithm: copy(iter1, iter2, objectB) • Copies each element from object A to object B • Starting with the location specified by the object A’s iterator in the 1st argument • Ending before (not including) the location specified by the Object B’s iterator in the 2nd argument
Vector Sequence Container • Class vector is a data structure with continuous memory locations • Same as an array • Can use the subscript operator [ ], as well as the at( ) member function • Use function push_back() to add elements to the end of the vector object • See examples vector1.txt & vector2.txt
#include <iostream> #include <vector> using std::cout; using std::cin; using std::endl; template <class T> void print(const std::vector<T> &vec){ std::vector<T>::const_iterator vi; for( vi =vec.begin();vi !=vec.end();vi++ ) cout << *vi << ' '; } void main(){ std::vector<int> v; cout<<"v.size() = "<< v.size()<<endl; //=0 v.push_back(10); v.push_back(20); v.push_back(30); cout<<"v.size() = "<< v.size()<<endl; //=3 print(v);//10 20 30 }
Vector Program v.size() • Returns the number of elements currently stored in the container void print(const std::vector<T> &vec){ • A constant reference to vector of type T std::vector<T>::const_iterator vi; • Defines a constant iterator vi that is used to iterate through the vector for(vi=vec.begin(); vi!=vec.end(); vi++) • A loop that starts at the beginning of the vector & ends once it counts past the end of the vector after 2nd element in the vector cout << *vi << ' '; • Outputs the value which the iterator vi points to
#include <iostream> #include <vector> #include <algorithm> using std::cout; using std::endl; void main(){ const int SIZE = 5; char ch[SIZE] = {'a','b','c','d','e'}; std::vector<char> v(ch, ch+SIZE); std::ostream_iterator<char> output(cout," "); cout<<"Vector v = "; std::copy(v.begin(),v.end(),output);//a b c d e v[0] = 'F';//set first element to 'F' v.insert(v.begin()+2,'G');//insert 3nd element v.erase(v.end()-1);//delete last element cout<<"\nVector v = "; std::copy(v.begin(),v.end(),output);//F b G c d v.clear(); cout<<v.empty()<<endl;} //1
Vector Program II std::ostream_iterator<char> output(cout," "); • Defines an ostream_iterator called output that can be used to output characters to the screen std::copy(v.begin(),v.end(),output); • Uses algorithm copy from the STL to output the contents of vector v to the screen v[0] = 'F'; • Just like an array v.insert(v.begin() + 2,'G'); • Insert after 2nd element in the vector v.clear(); • Delete all the elements in the vector
Class Exercise 1 • What’s the output of the program? • See exercise1.txt
Map Associative Container • The map associative container is used for fast storage & retrieval of unique keys & associated values • Duplicate keys are not allowed • Only a single value for each key • Called one-to-one mapping • For example (See map.txt) • A company with unique employee numbers (100, 200, 300) might have a map for their telephone extensions (4567, 4523, 4593)
#include <iostream> using std::cout; using std::endl; #include <map> void main(){ typedef std::map<int,double,std::less<int> > mapType; mapType m; m.insert( mapType::value_type( 50, 5.55 )); m.insert( mapType::value_type( 50, 777.7 )); m.insert( mapType::value_type( 10, 1010.10 )); m[10] = 1.11; m.insert( mapType::value_type( 20, 2.22 )); cout<<"m.size() = "<<m.size()<<endl; mapType::const_iterator it; for(it=m.begin();it!=m.end();++it) cout<<it->first<<'\t'<<it->second<<endl; } m.size() = 3 10 1.11 20 2.22 50 5.55
Map Program typedef std::map<int,double,std::less<int>> mapType; mapType m; • Use a typedef to create a new type name (alias) for map • Makes the code with long type names easier to read • Less<int> is a comparator function object • Sorts the keys in ascending order m.insert( mapType::value_type( 50, 5.55 )); • Creates a map object in which first (50) is the key of type int & second (5.55) is value of type double mapType::const_iterator it; for(it=m.begin();it!=m.end();++it) cout<<it->first<<'\t'<<it->second<<endl; • Uses a constant iterator to access the members of the object m in each element of the map
Stack Container Adapter • Last-in-first-out data structure • Member functions • push() • pop() • empty() • top() • size() • See stack.txt
#include <iostream> using std::cout; using std::endl; #include <stack> template< class T > void popAll(T &s); void main(){ std::stack< int > s; for(int i=1; i<=5; ++i) s.push(i); cout<<"s.size()="<<s.size()<<endl; //s.size()=5 popAll(s); //5 4 3 2 1 } template< class T > void popAll(T &s){ while(!s.empty()) { cout << s.top() << ' '; s.pop(); } }
Algorithms (search.txt) • Basic searching and sorting algorithms • find (iterator1, iterator2, element) • Find the location of the element from iterator1 and up to (but not including) interator2. Returns an iterator. • find_if (iterator1, iterator2, function) • Find the location where the function returns true • sort (iterator1, iterator2) • Sorts the elements between the two iterators • binary search (iterator1, iterator2, element) • Used when elements are already sorted in ascending order
Class Exercise 2 • Write a program that prompts the user to enter 5 integers, put the integers into a vector, sort the integers, and prints the vector