/* The following code example is taken from the book * "The C++ Standard Library - A Tutorial and Reference" * by Nicolai M. Josuttis, Addison-Wesley, 1999 * * (C) Copyright Nicolai M. Josuttis 1999. * Permission to copy, use, modify, sell and distribute this software * is granted provided this copyright notice appears in all copies. * This software is provided "as is" without express or implied * warranty, and with no claim as to its suitability for any purpose. */ #if 0 ////////// cont/vector1.cpp p156 #pragma warning( disable : 4786 ) #include #include #include #include using namespace std; int main() { // create empty vector for strings vector sentence; // reserve memory for five elements to avoid reallocation sentence.reserve(5); // append some elements sentence.push_back("Hello,"); sentence.push_back("how"); sentence.push_back("are"); sentence.push_back("you"); sentence.push_back("?"); // print elements separated with spaces copy (sentence.begin(), sentence.end(), ostream_iterator(cout," ")); cout << endl; // print ``technical data'' cout << " max_size(): " << sentence.max_size() << endl; cout << " size(): " << sentence.size() << endl; cout << " capacity(): " << sentence.capacity() << endl; // swap second and fourth element swap (sentence[1], sentence[3]); // insert element "always" before element "?" sentence.insert (find(sentence.begin(),sentence.end(),"?"), "always"); // assign "!" to the last element sentence.back() = "!"; // print elements separated with spaces copy (sentence.begin(), sentence.end(), ostream_iterator(cout," ")); cout << endl; // print "technical data" again cout << " max_size(): " << sentence.max_size() << endl; cout << " size(): " << sentence.size() << endl; cout << " capacity(): " << sentence.capacity() << endl; return 0; } // Hello, how are you ? // max_size(): 268435455 // size(): 5 // capacity(): 5 // Hello, you are how always ! // max_size(): 268435455 // size(): 6 // capacity(): 10 ////////// cont/deque1.cpp p164 #pragma warning( disable : 4786 ) #include #include #include #include using namespace std; int main() { // create empty deque of strings deque coll; // insert several elements coll.assign (3, string("string")); coll.push_back ("last string"); coll.push_front ("first string"); // print elements separated by newlines copy (coll.begin(), coll.end(), ostream_iterator(cout,"\n")); cout << endl; // remove first and last element coll.pop_front(); coll.pop_back(); // insert "another" into every element but the first for (int i=1; i(cout,"\n")); return 0; } // first string // string // string // string // last string // // string // another string // another string // resized string ////////// cont/list1.cpp p172 #include #include #include using namespace std; void printLists (const list& l1, const list& l2) { cout << "list1: "; copy (l1.begin(), l1.end(), ostream_iterator(cout," ")); cout << endl << "list2: "; copy (l2.begin(), l2.end(), ostream_iterator(cout," ")); cout << endl << endl; } int main() { // create two empty lists list list1, list2; // fill both lists with elements for (int i=0; i<6; ++i) { list1.push_back(i); list2.push_front(i); } printLists(list1, list2); // insert all elements of list1 before the first element with value 3 of list2 // - find() returns an iterator to the first element with value 3 list2.splice(find(list2.begin(),list2.end(), // destination position 3), list1); // source list printLists(list1, list2); // move first element to the end list2.splice(list2.end(), // destination position list2, // source list list2.begin()); // source position printLists(list1, list2); // sort second list, assign to list1 and remove duplicates list2.sort(); list1 = list2; list2.unique(); printLists(list1, list2); // merge both sorted lists into the first list list1.merge(list2); printLists(list1, list2); return 0; } // list1: 0 1 2 3 4 5 // list2: 5 4 3 2 1 0 // // list1: // list2: 5 4 0 1 2 3 4 5 3 2 1 0 // // list1: // list2: 4 0 1 2 3 4 5 3 2 1 0 5 // // list1: 0 0 1 1 2 2 3 3 4 4 5 5 // list2: 0 1 2 3 4 5 // // list1: 0 0 0 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 // list2: ////////// cont/set2.cpp p180 // lower_bound() returns the position of the first element that has // the same or a greater value than the argument. upper_bound() // returns the position of the first element with a greater value. #pragma warning( disable : 4786 ) #include #include using namespace std; int main () { set c; c.insert(1); c.insert(2); c.insert(4); c.insert(5); c.insert(6); cout << "lower_bound(3): " << *c.lower_bound(3) << endl; cout << "upper_bound(3): " << *c.upper_bound(3) << endl; cout << "equal_range(3): " << *c.equal_range(3).first << " " << *c.equal_range(3).second << endl; cout << endl; cout << "lower_bound(5): " << *c.lower_bound(5) << endl; cout << "upper_bound(5): " << *c.upper_bound(5) << endl; cout << "equal_range(5): " << *c.equal_range(5).first << " " << *c.equal_range(5).second << endl; return 0; } // lower_bound(3): 4 // upper_bound(3): 4 // equal_range(3): 4 4 // // lower_bound(5): 5 // upper_bound(5): 6 // equal_range(5): 5 6 ////////// cont/set1.cpp p186 #pragma warning( disable : 4786 ) #include #include using namespace std; int main() { /* type of the collection: * - no duplicates * - elements are integral values * - descending order */ typedef set > IntSet; IntSet coll1; // empty set container // insert elements in random order coll1.insert(4); coll1.insert(3); coll1.insert(5); coll1.insert(1); coll1.insert(6); coll1.insert(2); coll1.insert(5); // iterate over all elements and print them IntSet::iterator pos; for (pos = coll1.begin(); pos != coll1.end(); ++pos) { cout << *pos << ' '; } cout << endl; // insert 4 again and process return value pair status = coll1.insert(4); if (status.second) { cout << "4 inserted as element " << distance(coll1.begin(),status.first) + 1 << endl; } else { cout << "4 already exists" << endl; } // assign elements to another set with ascending order set coll2; copy (coll1.begin(), coll1.end(), inserter(coll2, coll2.end())); // print all elements of the copy copy (coll2.begin(), coll2.end(), ostream_iterator(cout," ")); cout << endl; // remove all elements up to element with value 3 coll2.erase (coll2.begin(), coll2.find(3)); // remove all elements with value 5 int num; num = coll2.erase (5); cout << num << " element(s) removed" << endl; // print all elements copy (coll2.begin(), coll2.end(), ostream_iterator(cout," ")); cout << endl; return 0; } // 6 5 4 3 2 1 // 4 already exists // 1 2 3 4 5 6 // 1 element(s) removed // 3 4 6 ////////// cont/mset1.cpp p189 #pragma warning( disable : 4786 ) #include #include using namespace std; int main() { /* type of the collection: * - duplicates allowed * - elements are integral values * - descending order */ typedef multiset > IntSet; IntSet coll1; // empty multiset container // insert elements in random order coll1.insert(4); coll1.insert(3); coll1.insert(5); coll1.insert(1); coll1.insert(6); coll1.insert(2); coll1.insert(5); // iterate over all elements and print them IntSet::iterator pos; for (pos = coll1.begin(); pos != coll1.end(); ++pos) { cout << *pos << ' '; } cout << endl; // insert 4 again and process return value IntSet::iterator ipos = coll1.insert(4); cout << "4 inserted as element " << distance(coll1.begin(),ipos) + 1 << endl; // assign elements to another multiset with ascending order multiset coll2; copy (coll1.begin(), coll1.end(), inserter(coll2, coll2.end())); // print all elements of the copy copy (coll2.begin(), coll2.end(), ostream_iterator(cout," ")); cout << endl; // remove all elements up to element with value 3 coll2.erase (coll2.begin(), coll2.find(3)); // remove all elements with value 5 int num; num = coll2.erase (5); cout << num << " element(s) removed" << endl; // print all elements copy (coll2.begin(), coll2.end(), ostream_iterator(cout," ")); cout << endl; return 0; } // 6 5 5 4 3 2 1 // 4 inserted as element 5 // 1 2 3 4 4 5 5 6 // 2 element(s) removed // 3 4 4 6 ////////// cont/setcmp.cpp p191 #pragma warning( disable : 4786 ) #include #include #include "print.hpp" using namespace std; // type for sorting criterion template class RuntimeCmp { public: enum cmp_mode {normal, reverse}; private: cmp_mode mode; public: // constructor for sorting criterion // - default criterion uses value normal RuntimeCmp (cmp_mode m=normal) : mode(m) { } // comparision of elements bool operator() (const T& t1, const T& t2) const { return mode == normal ? t1 < t2 : t2 < t1; } // comparision of sorting criteria bool operator== (const RuntimeCmp& rc) { return mode == rc.mode; } }; // type of a set that uses this sorting criterion typedef set > IntSet; // forward declaration void fill (IntSet&); int main() { // create, fill, and print set with normal element order // - uses default sorting criterion IntSet coll1; fill(coll1); PRINT_ELEMENTS (coll1, "coll1: "); // create sorting criterion with reverse element order RuntimeCmp reverse_order(RuntimeCmp::reverse); // create, fill, and print set with reverse element order // [see p197 and p213 for sorting criterion initialization] IntSet coll2(reverse_order); fill(coll2); PRINT_ELEMENTS (coll2, "coll2: "); // assign elements AND sorting criterion coll1 = coll2; coll1.insert(3); PRINT_ELEMENTS (coll1, "coll1: "); // just to make sure... if (coll1.value_comp() == coll2.value_comp()) { cout << "coll1 and coll2 have same sorting criterion" << endl; } else { cout << "coll1 and coll2 have different sorting criterion" << endl; } return 0; } void fill (IntSet& sett) { // fill insert elements in random order sett.insert(4); sett.insert(7); sett.insert(5); sett.insert(1); sett.insert(6); sett.insert(2); sett.insert(5); } // coll1: 1 2 4 5 6 7 // coll2: 7 6 5 4 2 1 // coll1: 7 6 5 4 3 2 1 // coll1 and coll2 have same sorting criterion ////////// cont/map1.cpp p207 #pragma warning( disable : 4786 ) #include #include #include using namespace std; int main() { /* create map / associative array * - keys are strings * - values are floats */ typedef map StringFloatMap; StringFloatMap stocks; // create empty container // insert some elements stocks["BASF"] = 369.50; stocks["VW"] = 413.50; stocks["Daimler"] = 819.00; stocks["BMW"] = 834.00; stocks["Siemens"] = 842.20; // print all elements StringFloatMap::iterator pos; for (pos = stocks.begin(); pos != stocks.end(); ++pos) { cout << "stock: " << pos->first << "\t" << "price: " << pos->second << endl; } cout << endl; // boom (all prices doubled) for (pos = stocks.begin(); pos != stocks.end(); ++pos) { pos->second *= 2; } // print all elements for (pos = stocks.begin(); pos != stocks.end(); ++pos) { cout << "stock: " << pos->first << "\t" << "price: " << pos->second << endl; } cout << endl; /* rename key from "VW" to "Volkswagen" * - only provided by exchanging element */ stocks["Volkswagen"] = stocks["VW"]; stocks.erase("VW"); // print all elements for (pos = stocks.begin(); pos != stocks.end(); ++pos) { cout << "stock: " << pos->first << "\t" << "price: " << pos->second << endl; } return 0; } // stock: BASF price: 369.5 // stock: BMW price: 834 // stock: Daimler price: 819 // stock: Siemens price: 842.2 // stock: VW price: 413.5 // // stock: BASF price: 739 // stock: BMW price: 1668 // stock: Daimler price: 1638 // stock: Siemens price: 1684.4 // stock: VW price: 827 // // stock: BASF price: 739 // stock: BMW price: 1668 // stock: Daimler price: 1638 // stock: Siemens price: 1684.4 // stock: Volkswagen price: 827 ////////// cont/mmap1.cpp p209 #pragma warning( disable : 4786 ) #include #include #include #include using namespace std; int main() { // define multimap type as string/string dictionary typedef multimap StrStrMMap; // create empty dictionary StrStrMMap dict; // insert some elements in random order dict.insert(make_pair(string("day"),string("Tag"))); dict.insert(make_pair(string("strange"),string("fremd"))); dict.insert(make_pair(string("car"),string("Auto"))); dict.insert(make_pair(string("smart"),string("elegant"))); dict.insert(make_pair(string("trait"),string("Merkmal"))); dict.insert(make_pair(string("strange"),string("seltsam"))); dict.insert(make_pair(string("smart"),string("raffiniert"))); dict.insert(make_pair(string("smart"),string("klug"))); dict.insert(make_pair(string("clever"),string("raffiniert"))); // print all elements StrStrMMap::iterator pos; cout.setf (ios::left, ios::adjustfield); cout << ' ' << setw(10) << "english " << "german " << endl; cout << setfill('-') << setw(20) << "" << setfill(' ') << endl; for (pos = dict.begin(); pos != dict.end(); ++pos) { cout << ' ' << setw(10) << pos->first.c_str() << pos->second << endl; } cout << endl; // print all values for key "smart" string word("smart"); cout << word << ": " << endl; for (pos = dict.lower_bound(word); pos != dict.upper_bound(word); ++pos) { cout << " " << pos->second << endl; } // print all keys for value "raffiniert" word = "raffiniert"; cout << word << ": " << endl; for (pos = dict.begin(); pos != dict.end(); ++pos) { if (pos->second == word) { cout << " " << pos->first << endl; } } return 0; } // english german // -------------------- // car Auto // clever raffiniert // day Tag // smart elegant // smart raffiniert // smart klug // strange fremd // strange seltsam // trait Merkmal // // smart: // elegant // raffiniert // klug // raffiniert: // clever // smart ////////// cont/mapfind.cpp p211 #pragma warning( disable : 4786 ) #include #include #include using namespace std; /* function object to check the value of a map element */ template class value_equals { private: V value; public: // constructor (initialize value to compare with) value_equals (const V& v) : value(v) { } // comparison bool operator() (pair elem) { return elem.second == value; } }; int main() { typedef map FloatFloatMap; FloatFloatMap coll; FloatFloatMap::iterator pos; // fill container coll[1]=7; coll[2]=4; coll[3]=2; coll[4]=3; coll[5]=6; coll[6]=1; coll[7]=3; // search an element with key 3.0 pos = coll.find(3.0); // logarithmic complexity if (pos != coll.end()) { cout << pos->first << ": " << pos->second << endl; } // search an element with value 3.0 pos = find_if(coll.begin(),coll.end(), // linear complexity value_equals(3.0)); if (pos != coll.end()) { cout << pos->first << ": " << pos->second << endl; } return 0; } // 3: 2 // 4: 3 ////////// cont/mapcmp.cpp p213 #pragma warning( disable : 4786 ) #include #include #include #include #include using namespace std; /* function object to compare strings * - allows you to set the comparison criterion at runtime * - allows you to compare case insensitive */ class RuntimeStringCmp { public: // constants for the comparison criterion enum cmp_mode {normal, nocase}; private: // actual comparison mode const cmp_mode mode; // auxiliary function to compare case insensitive static bool nocase_compare (char c1, char c2) { return toupper(c1) < toupper(c2); } public: // constructor: initializes the comparison criterion RuntimeStringCmp (cmp_mode m=normal) : mode(m) { } // the comparison bool operator() (const string& s1, const string& s2) const { if (mode == normal) { return s1 StringStringMap; // function that fills and prints such containers void fillAndPrint(StringStringMap& coll); int main() { // create a container with the default comparison criterion StringStringMap coll1; fillAndPrint(coll1); // create an object for case-insensitive comparisons RuntimeStringCmp ignorecase(RuntimeStringCmp::nocase); // create a container with the case-insensitive comparisons criterion StringStringMap coll2(ignorecase); fillAndPrint(coll2); return 0; } void fillAndPrint(StringStringMap& coll) { // fill insert elements in random order coll["Deutschland"] = "Germany"; coll["deutsch"] = "German"; coll["Haken"] = "snag"; coll["arbeiten"] = "work"; coll["Hund"] = "dog"; coll["gehen"] = "go"; coll["Unternehmen"] = "enterprise"; coll["unternehmen"] = "undertake"; coll["gehen"] = "walk"; coll["Bestatter"] = "undertaker"; // print elements StringStringMap::iterator pos; cout.setf(ios::left, ios::adjustfield); for (pos=coll.begin(); pos!=coll.end(); ++pos) { cout << setw(15) << pos->first.c_str() << " " << pos->second << endl; } cout << endl; } // Bestatter undertaker // Deutschland Germany // Haken snag // Hund dog // Unternehmen enterprise // arbeiten work // deutsch German // gehen walk // unternehmen undertake // // arbeiten work // Bestatter undertaker // deutsch German // Deutschland Germany // gehen walk // Haken snag // Hund dog // Unternehmen undertake ////////// cont/array1.cpp p218 #include #include #include using namespace std; int main() { int coll[] = { 5, 6, 2, 4, 1, 3 }; // square all elements transform (coll, coll+6, // first source coll, // second source coll, // destination multiplies()); // operation // sort beginning with the second element sort (coll+1, coll+6); // print all elements copy (coll, coll+6, ostream_iterator(cout," ")); cout << endl; return 0; } // 25 1 4 9 16 36 ////////// cont/carray1.cpp p220 #include #include /********* #include "carray.hpp" *********/ #include template class carray { private: T v[thesize]; // fixed-size array of elements of type T public: // type definitions typedef T value_type; typedef T* iterator; typedef const T* const_iterator; typedef T& reference; typedef const T& const_reference; typedef size_t size_type; typedef ptrdiff_t difference_type; // iterator support iterator begin() { return v; } const_iterator begin() const { return v; } iterator end() { return v+thesize; } const_iterator end() const { return v+thesize; } // direct element access reference operator[](size_t i) { return v[i]; } const_reference operator[](size_t i) const { return v[i]; } // size is constant size_type size() const { return thesize; } size_type max_size() const { return thesize; } // conversion to ordinary array T* as_array() { return v; } }; /********* #include "carray.hpp" *********/ #include "print.hpp" using namespace std; int main() { carray a; for (unsigned i=0; i()); // operation PRINT_ELEMENTS(a); return 0; } // 1 2 3 4 5 6 7 8 9 10 // 10 9 8 7 6 5 4 3 2 1 // -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 ////////// cont/refsem1.cpp p224 #include #include #include #include /********* #include "countptr.hpp" *********/ #ifndef COUNTED_PTR_HPP #define COUNTED_PTR_HPP /* class for counted reference semantics * - deletes the object to which it refers when the last CountedPtr * that refers to it is destroyed */ template class CountedPtr { private: T* ptr; // pointer to the value long* count; // shared number of owners public: // initialize pointer with existing pointer // - requires that the pointer p is a return value of new explicit CountedPtr (T* p=0) : ptr(p), count(new long(1)) { } // copy pointer (one more owner) CountedPtr (const CountedPtr& p) throw() : ptr(p.ptr), count(p.count) { ++*count; } // destructor (delete value if this was the last owner) ~CountedPtr () throw() { dispose(); } // assignment (unshare old and share new value) CountedPtr& operator= (const CountedPtr& p) throw() { if (this != &p) { dispose(); ptr = p.ptr; count = p.count; ++*count; } return *this; } // access the value to which the pointer refers T& operator*() const throw() { return *ptr; } T* operator->() const throw() { return ptr; } private: void dispose() { if (--*count == 0) { delete count; delete ptr; } } }; #endif /*COUNTED_PTR_HPP*/ /********* #include "countptr.hpp" *********/ using namespace std; void printCountedPtr (CountedPtr elem) { cout << *elem << ' '; } int main() { // array of integers (to share in different containers) static int values[] = { 3, 5, 9, 1, 6, 4 }; // two different collections typedef CountedPtr IntPtr; deque coll1; list coll2; /* insert shared objects into the collections * - same order in coll1 * - reverse order in coll2 */ for (int i=0; i #include #include #include using namespace std; int main() { /* create a string set * - initialized by all words from standard input */ set coll; istream_iterator a(cin); istream_iterator b; copy (a, b, inserter(coll, coll.end())); // print all elements copy (coll.begin(), coll.end(), ostream_iterator(cout, "\n")); return 0; } // the first line // and the second // the last line // ^Z // // and // first // last // line // second // the ////////// cont/sortvec.cpp p229 #pragma warning( disable : 4786 ) #include #include #include #include using namespace std; int main() { /* create a string vector * - initialized by all words from standard input */ vector coll; istream_iterator a(cin); istream_iterator b; copy (a, b, inserter(coll, coll.end())); // sort elements sort (coll.begin(), coll.end()); // print all elements ignoring subsequent duplicates unique_copy (coll.begin(), coll.end(), ostream_iterator(cout, "\n")); return 0; } // the first line // and the second // the last line // ^Z // // and // first // last // line // second // the ////////// cont/stack1.cpp p437 #include #include using namespace std; int main() { stack st; // push three elements into the stack st.push(1); st.push(2); st.push(3); // pop and print two elements from the stack cout << st.top() << ' '; st.pop(); cout << st.top() << ' '; st.pop(); // modify top element st.top() = 77; // push two new elements st.push(4); st.push(5); // pop one element without processing it st.pop(); // pop and print remaining elements while (!st.empty()) { cout << st.top() << ' '; st.pop(); } cout << endl; return 0; } // 3 2 4 77 ////////// cont/stack2.cpp p443 #include /********* #include "Stack.hpp" *********/ /* ************************************************************ * Stack.hpp * - safer and more convenient stack class * ************************************************************/ #ifndef STACK_HPP #define STACK_HPP #include #include template class Stack { protected: std::deque c; // container for the elements public: /* exception class for pop() and top() with empty stack */ class ReadEmptyStack : public std::exception { public: virtual const char* what() const throw() { return "read empty stack"; } }; // number of elements typename std::deque::size_type size() const { return c.size(); } // is stack empty? bool empty() const { return c.empty(); } // push element into the stack void push (const T& elem) { c.push_back(elem); } // pop element out of the stack and return its value T pop () { if (c.empty()) { throw ReadEmptyStack(); } T elem(c.back()); c.pop_back(); return elem; } // return value of next element T& top () { if (c.empty()) { throw ReadEmptyStack(); } return c.back(); } }; #endif /* STACK_HPP */ /********* #include "Stack.hpp" *********/ using namespace std; int main() { try { Stack st; // push three elements into the stack st.push(1); st.push(2); st.push(3); // pop and print two elements from the stack cout << st.pop() << ' '; cout << st.pop() << ' '; // modify top element st.top() = 77; // push two new elements st.push(4); st.push(5); // pop one element without processing it st.pop(); /* pop and print three elements * - ERROR: one element too many */ cout << st.pop() << ' '; cout << st.pop() << endl; cout << st.pop() << endl; } catch (const exception& e) { cerr << "EXCEPTION: " << e.what() << endl; } return 0; } // 3 2 4 77 // EXCEPTION: read empty stack ////////// cont/queue1.cpp p446 #pragma warning( disable : 4786 ) #include #include #include using namespace std; int main() { queue q; // insert three elements into the queue q.push("These "); q.push("are "); q.push("more than "); // read and print two elements from the queue cout << q.front(); q.pop(); cout << q.front(); q.pop(); // insert two new elements q.push("four "); q.push("words!"); // skip one element q.pop(); // read and print two elements cout << q.front(); q.pop(); cout << q.front() << endl; q.pop(); // print number of elements in the queue cout << "number of elements in the queue: " << q.size() << endl; return 0; } // These are four words! // number of elements in the queue: 0 ////////// cont/queue2.cpp p452 #pragma warning( disable : 4786 ) #include #include /********* #include "Queue.hpp" *********/ /* ************************************************************ * Queue.hpp * - safer and more convenient queue class * ************************************************************/ #ifndef QUEUE_HPP #define QUEUE_HPP #include #include template class Queue { protected: std::deque c; // container for the elements public: /* exception class for pop() and top() with empty queue */ class ReadEmptyQueue : public std::exception { public: virtual const char* what() const throw() { return "read empty queue"; } }; // number of elements typename std::deque::size_type size() const { return c.size(); } // is queue empty? bool empty() const { return c.empty(); } // insert element into the queue void push (const T& elem) { c.push_back(elem); } // read element from the queue and return its value T pop () { if (c.empty()) { throw ReadEmptyQueue(); } T elem(c.front()); c.pop_front(); return elem; } // return value of next element T& front () { if (c.empty()) { throw ReadEmptyQueue(); } return c.front(); } }; #endif /* QUEUE_HPP */ /********* #include "Queue.hpp" *********/ using namespace std; int main() { try { Queue q; // insert three elements into the queue q.push("These "); q.push("are "); q.push("more than "); // read and print two elements from the queue cout << q.pop(); cout << q.pop(); // push two new elements q.push("four "); q.push("words!"); // skip one element q.pop(); // read and print two elements from the queue cout << q.pop(); cout << q.pop() << endl; // print number of remaining elements cout << "number of elements in the queue: " << q.size() << endl; // read and print one element cout << q.pop() << endl; } catch (const exception& e) { cerr << "EXCEPTION: " << e.what() << endl; } return 0; } // These are four words! // number of elements in the queue: 0 // EXCEPTION: read empty queue ////////// cont/pqueue1.cpp p455 #include #include using namespace std; int main() { priority_queue q; // insert three elements into the priority queue q.push(66.6); q.push(22.2); q.push(44.4); // read and print two elements cout << q.top() << ' '; q.pop(); cout << q.top() << endl; q.pop(); // insert three more elements q.push(11.1); q.push(55.5); q.push(33.3); // skip one element q.pop(); // pop and print remaining elements while (!q.empty()) { cout << q.top() << ' '; q.pop(); } cout << endl; return 0; } // 66.6 44.4 // 33.3 22.2 11.1 ////////// cont/bitset1.cpp p460 #include #include using namespace std; int main() { /* enumeration type for the bits * - each bit represents a color */ enum Color { red, yellow, green, blue, white, black, //..., numColors }; // create bitset for all bits/colors bitset usedColors; // set bits for two colors usedColors.set(red); usedColors.set(blue); // print some bitset data cout << "bitfield of used colors: " << usedColors << endl; cout << "number of used colors: " << usedColors.count() << endl; cout << "bitfield of unused colors: " << ~usedColors << endl; // if any color is used if (usedColors.any()) { // loop over all colors for (int c = 0; c < numColors; ++c) { // if the actual color is used if (usedColors[(Color)c]) { //... } } } return 0; } // bitfield of used colors: 001001 // number of used colors: 2 // bitfield of unused colors: 110110 ////////// cont/bitset2.cpp p462 #include #include #include #include using namespace std; int main() { /* print some numbers in binary representation */ cout << "267 as binary short: " << bitset::digits>(267) << endl; cout << "267 as binary long: " << bitset::digits>(267) << endl; cout << "10,000,000 with 24 bits: " << bitset<24>(1e7) << endl; /* transform binary representation into integral number */ cout << "\"1000101011\" as number: " << bitset<100>(string("1000101011")).to_ulong() << endl; return 0; } // 267 as binary short: 0000000100001011 // 267 as binary long: 00000000000000000000000100001011 // 10,000,000 with 24 bits: 100110001001011010000000 // "1000101011" as number: 555 #endif