cns 3370.  sequences  vector,deque,list,(string),forward_list  container adapters ...

Download CNS 3370.  Sequences  vector,deque,list,(string),forward_list  Container Adapters  queue, stack, priority_queue  Associative Containers  set, unordered_set

Post on 30-Dec-2015

215 views

Category:

Documents

2 download

Embed Size (px)

TRANSCRIPT

  • CNS 3370

  • Sequencesvector,deque,list,(string),forward_listContainer Adaptersqueue, stack, priority_queueAssociative Containersset, unordered_setmap, unordered_mapplus multi_ versions of each of the above

  • bool empty();// use instead of size() == 0size_t size();void resize(size_t, T = T()); T& front(); T& back();// Not forward_listvoid push_back(const T&);// Not forward_listvoid pop_back();// Not forward_list

  • // deque and list/forward_list only:void push_front(const T&);void pop_front();

    //deque, vector and string only:T& at(size_type n);// range-checkedT& operator[]shrink_to_fit();

  • Generalization of a pointerOverload at least operator!=, operator==, operator*, operator++, operator->Some overload operator--, operator[], pointer arithmetic

  • templateIterator find(Iterator start, Iterator past, const T& v){ while (start != past) { if (*start == v) break; ++start; } return start;} All algorithms are implemented in terms of iterators

  • InputOutputForwardBi-directionalRandom Access

  • Modeled after file inputRead-only access to elementsSingle-pass, forward traversalfind expects an Input Iteratorit only needs to read through the data once

  • templateInputIterator find(InputIterator start, InputIterator past, const T& v){ while (start != past) { if (*start == v) break; ++start; } return start;}

  • Modeled after file outputWrite-only access to elementsSingle-pass, forward traversalExample: ostream_iterator:copy(a, a+n, ostream_iterator(cout, ));

  • Both read and write accesscan be used as Input or Output IteratorsMultiple-pass, forward traversalunique expects a Forward Iterator list::iterator p = unique(lst.first(), lst.end());It needs 2 simultaneous, read/write iterators

  • Can do everything a Forward Iterator canAlso support backwards traversaloperator--()operator--(int)reverse requires a Bi-directional Iterator

  • list::iterator p = lst.end();while (p != lst.begin()){ --p;// advances backwards

    // process *p}

  • list::reverse_iterator p = lst.rbegin();while (p != lst.rend()){ // process *p, then: ++p;// advances backwards}

  • Modeled after pointerssupport Pointer Arithmetic in constant timeoperator+, +=, -, -=, [], =sort expects a Random Access Iterator

  • Functional inheritance via duck typing

    (not via classes)

  • Doesnt provide a Random Access IteratorGeneric sort will fail on a listAnswer:Provides its own sort member functionAlso merge, remove, and unique

  • vector v1;// fill v1, then:vector v2;copy(v1.begin(), v1.end(), v2.begin());

  • Iterators work in overwrite mode by defaultNeed an insert mode for cases like abovethat calls the appropriate insert operation provided by the container

  • Replace output calls (operator*, operator=, etc.) with appropriate insert functionback_insert_iteratorcalls push_backfront_insert_iteratorcalls push_frontinsert_iteratorcalls insert

  • vector v1;// fill v1, then:vector v2;copy(v1.begin(), v1.end(), back_inserter(v2));

    (But there is still a better way)

  • back_insertercreates a back_insert_iteratorfront_insertercreates a front_insert_iteratorinsertercreates an insert_iterator

  • ostream_iteratoran Output Iterator copy(v1.begin(), v1.end(), ostream_iterator(cout, ));istream_iteratoran Input Iteratorcopy(istream_iterator(cin), istream_iterator(), back_inserter(v1));

  • insert, assign, erase, and constructorsUsually more efficient than the generic algorithm counterpartsPrefer over using copySee range-based.cpp

  • For erasing selected elements of a sequenceapplies to vector, deque, stringfor lists, use remove/remove_ifThe idiom:The remove algorithm reorders the sequence, moving the deleted elements to the endreturning an iterator to the first deleted elementc.erase(remove(beg, end, x), end);c.erase(remove_if(beg, end, pred), end);

  • Higher-level Containers that use Sequences

  • High-level abstract data typesqueue, stack, priority_queueThey adapt sequences for specific usesi.e., they use a sequence for implementationstack & queue use deque by defaultpriority_queue uses a vectorcan change the underlying sequence:stack myStack;No iterators are providedthey offer a more restricted interface

  • queue:pushes at end, pops from frontfront, back, push, popstack:pushes and pops at fronttop, push, poppriority_queue: (See pq.cpp, pq2.cpp)retrieves elements in priority orderyou provide a strict weak ordering

  • priority_queue and ordered associative containers (set, map, multi_set, multi_map) require strict weak ordering comparatorsbehave like less< >( ) ( (which calls operator
  • Two flavorsOrderedtree-based storage O(log n) retrievalset, multi_set, map, multi_mapUnorderedhashed-based storageO(1) retrievalunordered_set, unordered_map

  • #include #include #include using namespace std;

    int main(){ // Populate a set: set s; s.insert("Alabama"); s.insert("Georgia"); s.insert("Tennessee"); s.insert("Tennessee");

  • // Print it out: auto p = s.begin(); while (p != s.end()) cout
  • // Output:AlabamaGeorgiaTennessee

    found Alabamadidn't find Michigan

  • #include #include #include using namespace std;

    int main(){ // Insert some elements (two ways): map m; m.insert(make_pair(string("Alabama"), string("Montgomery"))); m["Georgia"] = "Atlanta"; m["Tennessee"] = "Knoxville"; m["Tennessee"] = "Nashville"; // overwrites

  • // Print the map: auto p = m.begin(); while (p != m.end()) { auto elem = *p++; cout

  • // Retrieve via a key: cout

  • Shows the conciseness of maps designCount the number of each word in a text filewordcount.cppoutput in wordcount-gettysburg.out

  • Necessary to maintain proper order in the underlying tree data structureThey test for equivalence, not equality, to maintain uniquenessx and y are equivalent iff !cmp(x,y) && !cmp(y,x)i.e., neither precedes the otherExample:swo.cppignores non-alpha characters in strings

    Illustrate by reading and writing items (numbers then strings) from files. back_inserter is useful with file i/o since we dont know the size ahead of time. Otherwise, append is better.*Explain that priority_queue uses a heap data structure, which doesnt perform a full sort, and is therefore more efficient than sorting a sequence. Comparators must implement a strict weak ordering. *Just think less-than to understand SWOs.*insert doesnt overwrite.*In swo.cpp, change the < to