660 likes | 1.09k Views
C++ STL Containers - Iterators. Gathered by Dr. Mohammad Nassef CS-FCI-CU-EG m.nassef@fci-cu.edu.eg. What Is STL?. Standard Template Library C++ based implementations of general purpose data structures and algorithms. Beginning?.
E N D
C++ STLContainers - Iterators Gathered by Dr. Mohammad Nassef CS-FCI-CU-EG m.nassef@fci-cu.edu.eg
What Is STL? • Standard Template Library • C++ based implementations of general purpose data structures and algorithms
Beginning? • In 1990, Alex Stepanov and Meng Lee of Hewlett Packard Laboratories extended C++ with a library of class and function templates which has come to be known as the STL. • In 1994, STL was adopted as part of ANSI/ISO Standard C++.
What does STL contain? • STL had three basic components: • Containers Generic class templates for storing collection of data. • Algorithms Generic function templates for operating on containers. • Iterators Generalized ‘smart’ pointers that facilitate use of containers. They provide an interface that is needed for STL algorithms to operate on STL containers. • String abstraction was added during standardization. • It is a template library! • Designed for high-level programming • Designed for efficient programming
When Do You Need STL? • Reduce your C/C++ programming time • Use data structures and algorithms from STL directly, instead of implementing everything from scratch • Easier maintenance • Bugs in bottom structures are the most difficult to find • Use STL as building blocks, they are robust • Program runtime is not very critical • General purpose implementations may run a little slower than customized implementations
STL Containers: 3 Types • Sequence Container • Stores data by position in linear order: • First element, second element , etc: • Sequence Container Examples: • Vector • Deque • List
STL Containers: 3 Types • Adapter Container • Contains another container as its underlying storage structure • Adapter Containers Examples: • Stack • Queue • Priority queue
STL Containers: 3 Types • Associate Container • Stores elements by key, such as name, social security number or part number • Access an element by its key which may bear no relationship to the location of the element in the container • Associative Container Examples: • Set, multiset • Map, multimap
Containers Header Files? • The following are the header files for several basic kinds of containers: • <vector> : one-dimensional array • <list> : double linked list • <deque> : double-ended queue • <queue> : queue • <stack> : stack • <set> : set • <map> : associative array
Vector Container • Generalized array that stores a collection of elements of the same data type • Vector – similar to an array • Vectors allow access to its elements by using an index in the range from 0 to n-1 where n is the size of the vector • Vector vs array • Vector has operations that allow the collection to grow dynamically at the rear of the sequence
vector vs. array in C/C++ • Dynamic memory management for vector • Certain size of memory is allocated when a vector is constructed • When add a new element and the memory space is insufficient, multiple-sized new memory is allocated automatically
Defining a new vector Syntax: vector<of what> For example : vector<int> - vector of integers. vector<string> - vector of strings. vector<int *> - vector of pointers to integers. vector<Shape> - vector of Shape objects. Shape is a user defined class.
Constructors for Vector • A vector can be initialized by specifying its size and a prototype element or by another vector vector<Date> x(1000); // creates vector of size 1000, // requires default constructor for Date vector<Date> dates(10,Date(17,12,1999)); // initializes // all elements with 17.12.1999 vector<Date> y(x); // initializes vector y with vector x
Vector Container Example: #include <vector> . . . vector<int> scores (100); //100 integer scores vector<Passenger> passengerList(20); //list of 20 passengers
Using Vector • #include <vector> • Two ways to use the vector type: • Array style. • STL style
Using a Vector – Array Style We mimic the use of built-in array. void simple_example(){const int N = 10; vector<int> ivec(N); for (int i=0; i < 10; ++i) cin >> ivec[i]; // normal array int ia[N];for ( int j = 0; j < N; ++j) ia[j] = ivec[j];}
Vector Container • Example: #include <vector> vector <int> v(20); v[5]=15;
Insertion void push_back(const T& x); Inserts an element with value x at the end of the controlled sequence. svec.push_back(str);
Using a vector – STL style You can define an empty vectorvector<string> svec;Then insert elements into the vector using the method push_back. string word;while ( cin >> word ) //the number of // words is unlimited. { svec.push_back(word);}
Size unsigned intsize(); Returns the length of the controlled sequence (how many items it contains). unsigned int size = svec.size();
Vector Container int array[5] = {12, 7, 9, 21, 13 }; vector<int> v(array,array+5); 12 7 9 21 13 v.push_back(15); v.pop_back(); 13 … 12 7 9 21 12 7 9 21 15 0 1 2 3 4 12 7 9 21 15 v.begin(); v[3]
Vector Container #include <vector> #include <iostream> vector<int> v(3); // create a vector of ints of size 3 v[0]=23; v[1]=12; v[2]=9; // vector full v.push_back(17); // put a new value at the end of array for (int i=0; i<v.size(); i++) // member function size() of vector cout << v[i] << ” ”; // random access to i-th element cout << endl;
Vector Container #include <vector> #include <iostream> int arr[] = { 12, 3, 17, 8 }; // standard C array vector<int> v(arr, arr+4); // initialize vector with C++ array while ( ! v.empty()) // until vector is empty { cout << v.back() << ” ”; // output last element of vector v.pop_back(); // delete the last element } cout << endl;
Advantages and Disadvantages of Vector • fastpush_back() • fast operator[] • slow insert()
STL vector • No push_front(), pop_front(), remove(), sort(), merge() • Supports operator [], such as vectorA[3] • Thenwhy need vector ? • Faster access if the data are mostly static or not much insertion/deletion
STL deque • Very similar to vector, except • Supports push_front() and pop_front() • Also friendly to accessing static data
Vector vs. Deque vs. List • Contiguous-memory based: • vector, constant time addition and deletion at end • deque, constant time addition and deletion at beginning and end • Constant time access • Linear time insertion/deletion in middle • Node based – list • Linear time access • Constant time insertion/deletion any position
empty() vs. size() == 0 • Two methods to check if a container is empty • empty(), takes constant time • Check if size() == 0, may take linear time!
List Container • Stores elements by position • Each item in the list has both a value and a memory address (pointer) that identifies the next item in the sequence • In the Data Structures course, you will learn how to build a (Linked) List class that internally links successive notes to each other. • To access a specific data value in the list, one must start at the first position (front) and follow the pointers from element to element until data item is located. (called list traversal) • Real life examples???
List Container • List is not a direct access structure • Advantage: ability to add and remove items efficiently at any position in the sequence • Useful for: • Insertion • Deletion • Sorting
List Container int array[5] = {12, 7, 9, 21, 13 }; list<int> li(array,array+5); 12 7 9 21 13 li.push_back(15); li.pop_back(); 13 … 12 7 9 21 12 7 9 21 15 li.pop_front(); li.push_front(8); 12 … 8 12 7 9 21 15 7 9 21 li.insert() 19 7 12 17 21 23
class node { private: long x, y, ID; double rat, cap; node* parent; public: node(long id); void setCoordinates( long, long ); long getID(); }; node::node(long id) : x(0), y(0), ID(id), parent(NULL) {} long node::getID() { return ID; } main() { node myNode(1); myNode.setCoordinates(5,8); long p = myNode.getID(); } Example of class
Example of list #include <list.h> void doSomething() { list<node> nodeList; … … nodeList.push_back( node(1) ); // node1 is added at end nodeList.push_front( node(0) ); // node0 is added at front nodeList.pop_back(); // remove the element at end nodeList.pop_front(); // remove the element at front … … }
Adapter Containers • STL supports three container adapters: • stack, queue and priority_queue • They are implemented using the containers seen before • They do not provide actual data structure • Container adapters do not support iterators • The functions push and pop are common to all container adapters SEG4110 - Topic J - C++ Standard Template Library
Stack Container • Adapter Container • Internally uses another container to manage elements • In the Data Structures course, you will learn how to build a stack class that internally uses an array or a list. • Stack restricts how elements enter and leave a sequence • Stack • allows access at only one end of the sequence (top) • Adds objects to container by pushing the object onto the stack • Removes objects from container by popping the stack • LIFO ordering (last end, first out)
Queue Container • Queue • Allows access only at the front and rear of the sequence • Items enter at the rear and exit from the front • Example: waiting line at a grocery store • FIFO ordering (first-in first-out ) • push(add object to a queue) .. Also called enqueue • pop (remove object from queue) .. Also called dequeue • In the Data Structures course, you will learn how to build a queue class that internally uses an array or a list.
Priority Queue Container • Priority queue • Operations are similar to those of a stack or queue • Elements can enter the priority queue in any order • Once in the container, a delete operation removes the largest (or smallest) value (according to the element’s priority)
Set Container • Collection of unique values, called keys or set members • Contains operations that allow a programmer to: • determine whether an item is a member of the set • insert and delete items very efficiently • Sets use hash tables internally to find items very quickly. • You will learn about Hash Tables in the Data Structures course. Set A Set B • 1 3 • 27 15 Buick Ford Jeep BMW
Multi-Set Container • A multi-set is similar to a set, but the same value can be in the set more than once • Multi-set container allows duplicates
Map Container • Implements a key-value relationship • Programmer can use a key to access corresponding values • Example: key could be a part number such as A24-57 that corresponds to a part: 8.75 price and Martin manufacturer
Map Example • Maps are sorted collections in which the actual position of an element depends on its value due to a sorting criterion.
Multi-map Container • Similar to a map container • Multi-map container allows duplicates
How to access Container elements? Iterator • Definition? • Iterator is an object that can access a collection of similar objects, one object at a time. • Iterators are pointer-like entities that are used to access individual elements in a container. • An iterator can traverse the collection of objects. • Each container class in STL has a corresponding iterator that functions appropriately for the container. • For example: • an iterator in a vector class allows random access • An iterator in a list class would not allow random access (list requires sequential access)
Iterators • Often they are used to move sequentially from element to element, a process called iterating through (or traversing) a container. vector<int> array_ 17 vector<int>::iterator 4 23 The iterator corresponding to the class vector<int> is of the type: vector<int>::iterator 12 size_ 4
Iterators • The member functions begin() and end() return an iterator to the first and past the last element of a container vector<int> v v.begin() array_ 17 4 23 v.end() 12 size_ 4
Iterators • One can have multiple iterators pointing to different or identical elements in the container vector<int> v i1 array_ 17 4 i2 23 12 i3 size_ 4
Common Iterator Operations * Return the item that the iterator currently references ++ Move the iterator to the next item in the list -- Move the iterator to the previous item in the list == Compare two iterators for equality != Compare two iterators for inequality
Vector Iterator Example 1 #include <vector> #include <iostream> int arr[] = { 12, 3, 17, 8 }; // standard C++ array vector<int> v(arr, arr+4); // initialize vector with C++ array vector<int>::iterator iter = v.begin(); // iterator for class vector // define iterator for vector and point it to first element of v cout << ”first element of v=” << *iter; // de-reference iter iter++; // move iterator to next element iter=v.end()-1; // move iterator to last element
Vector Iterator Example 2 int max(vector<int>::iterator start, vector<int>::iterator stop) { int m=*start; while(start != stop) { if (*start > m) m=*start; ++start; } return m; } cout << ”max of v = ” << max(v.begin(),v.end());
Vector Iterator Example 3 #include <vector> #include <iostream> int arr[] = { 12, 3, 17, 8 }; // standard C array vector<int> v(arr, arr+4); // initialize vector with C array // initialize i with pointer to first element of v // i++ increment iterator, move iterator to next element for (vector<int>::iterator i=v.begin(); i != v.end(); i++) { cout << *i << ” ”; // de-referencing iterator returns the // value of the element the iterator points at } cout << endl;