first commit

This commit is contained in:
Jose Caban
2025-06-07 11:34:38 -04:00
commit 0eb2d7c07d
4708 changed files with 1500614 additions and 0 deletions

View File

@@ -0,0 +1,242 @@
/**************************************************************************
*
* alg1.cpp - Example program for STL generic algorithms that initialize
* sequences.
*
* $Id: alg1.cpp 550991 2007-06-26 23:58:07Z sebor $
*
***************************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* Copyright 1994-2006 Rogue Wave Software.
*
**************************************************************************/
#include <vector> // for vector
#include <list> // for list
#include <algorithm> // for copy(), fill(), generate(), swap()
#include <string> // for string
#include <iostream> // for cout
#include <iterator> // for ostream_iterator
#include <sstream> // for stringstream
#include <examples.h>
typedef std::ostream_iterator<int, char,
std::char_traits<char> > int_ostrm_iter;
typedef std::ostream_iterator<std::string, char,
std::char_traits<char> > str_ostrm_iter;
typedef std::ostream_iterator<char, char,
std::char_traits<char> > char_ostrm_iter;
class iotaGen
{
public:
iotaGen (int iv) : current (iv)
{ }
int operator () () {
return current++;
}
private:
int current;
};
// Illustrate the use of the fill and fill_n functions.
void fill_example ()
{
std::cout << "Illustrate fill function\n";
// Example 1, fill an array with initial values
char buffer [100];
char *bufferp = buffer;
std::fill (bufferp, (bufferp + 100), '\0');
std::fill_n (bufferp, 10, 'x');
std::cout << buffer << '\n';
// Example 2, use fill to initialize a std::list.
std::list<std::string, std::allocator<std::string> > aList;
std::fill_n (std::inserter (aList, aList.begin ()), 10, "empty");
std::copy (aList.begin (), aList.end (),
str_ostrm_iter (std::cout, " "));
std::cout << '\n';
// Example 3, use fill to overwrite values in a std::list.
std::fill (aList.begin (), aList.end (), "full");
std::copy (aList.begin (), aList.end (),
str_ostrm_iter (std::cout, " "));
std::cout << '\n';
// Example 4, fill in a portion of a std::list.
std::vector<int, std::allocator<int> > iVec (10);
std::generate (iVec.begin (), iVec.end (), iotaGen (1));
std::vector<int, std::allocator<int> >::iterator
seven = std::find (iVec.begin (), iVec.end (), 7);
std::fill (iVec.begin (), seven, 0);
std::copy (iVec.begin (), iVec.end (), int_ostrm_iter (std::cout));
std::cout << '\n';
}
// Illustrate the use of the copy function.
void copy_example ()
{
std::cout << "Illustrate copy function\n";
// Example 1, a simple copy.
const char source[] = "reprise";
const char surpass[] = "surpass";
char buffer [120];
char *bufferp = buffer;
std::copy (&source [0],
source + std::char_traits<char>::length (source) + 1, bufferp);
// Example 2, self copies.
*std::copy (bufferp + 2,
bufferp + std::char_traits<char>::length (buffer),
bufferp) = '\0';
std::size_t buflen = std::char_traits<char>::length (buffer) + 1;
std::copy_backward (bufferp,
bufferp + buflen, bufferp + buflen + 3);
std::copy (&surpass [0], surpass + 3, bufferp);
// Example 3, copy to output.
std::copy (bufferp, bufferp + std::char_traits<char>::length (buffer),
char_ostrm_iter (std::cout));
std::cout << '\n';
// Example 4, use copy to convert type.
std::list<char, std::allocator<char> > char_list;
const char big[] = "big ";
char buffer2 [200];
char *buffer2p = buffer2;
std::copy (bufferp, bufferp + std::char_traits<char>::length (buffer),
std::inserter (char_list, char_list.end ()));
std::copy (&big [0], big + 4,
std::inserter (char_list, char_list.begin ()));
*std::copy (char_list.begin (),
char_list.end (), buffer2p) = '\0';
std::cout << buffer2 << '\n';
}
std::string generateLabel ()
{
// Generate a label std::string of the form L_ddd.
static int lastLabel = 0;
std::ostringstream ost;
ost << "L_" << lastLabel++;
return ost.str ();
}
// Illustrate the use of the generate and genrate_n functions.
void generate_example ()
{
std::cout << "Illustrate generate algorithm\n";
// Example 1, generate a std::list of label numbers.
std::list<std::string, std::allocator<std::string> > labelList;
std::generate_n (std::inserter (labelList, labelList.begin ()),
4, generateLabel);
std::copy (labelList.begin (), labelList.end (),
str_ostrm_iter (std::cout, " "));
std::cout << '\n';
// Example 2, generate an arithmetic progression.
std::vector<int, std::allocator<int> > iVec (10);
std::generate (iVec.begin (), iVec.end (), iotaGen (2));
std::generate_n (iVec.begin (), 5, iotaGen (7));
std::copy (iVec.begin (), iVec.end (), int_ostrm_iter (std::cout, " "));
std::cout << '\n';
}
// Illustrate the use of the algorithm swap_ranges.
void swap_example ()
{
std::cout << "Illustrate swap_ranges algorithm\n";
// First make two parallel sequences.
int data[] = {12, 27, 14, 64}, *datap = data;
std::vector<int, std::allocator<int> > aVec (4);
std::generate (aVec.begin (), aVec.end (), iotaGen (1));
// Illustrate swap and iter_swap.
std::swap (data [0], data [2]);
std::copy (data, data + 4, int_ostrm_iter (std::cout, " "));
std::cout << '\n';
std::vector<int, std::allocator<int> >::iterator last =
aVec.end ();
--last;
std::iter_swap (aVec.begin (), last);
std::copy (aVec.begin (), aVec.end (),
int_ostrm_iter (std::cout, " "));
std::cout << '\n';
// Now swap the entire sequence.
std::swap_ranges (aVec.begin (), aVec.end (), datap);
std::copy (data, data+4, int_ostrm_iter (std::cout, " "));
std::cout << '\n';
std::copy (aVec.begin (), aVec.end (),
int_ostrm_iter (std::cout, " "));
std::cout << '\n';
}
int main ()
{
std::cout << "STL generic algorithms -- initialization algorithms\n";
fill_example ();
copy_example ();
generate_example ();
swap_example ();
std::cout << "End of initialization tests\n";
return 0;
}

View File

@@ -0,0 +1,217 @@
/**************************************************************************
*
* alg2.cpp - Examples using STL generic algorithms that search for
* elements that satisfy a condition.
*
* $Id: alg2.cpp 550991 2007-06-26 23:58:07Z sebor $
*
***************************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* Copyright 1994-2006 Rogue Wave Software.
*
**************************************************************************/
#include <vector>
#include <list>
#include <algorithm>
#include <string>
#include <cstring>
#include <iostream>
#include <examples.h>
void split (const std::string & text, const std::string & separators,
std::list<std::string, std::allocator<std::string> > & words) {
const std::string::size_type n = text.length ();
std::string::size_type start = text.find_first_not_of (separators);
while (start < n) {
std::string::size_type stop = text.find_first_of (separators, start);
if (stop > n)
stop = n;
words.push_back (text.substr (start, stop - start));
start = text.find_first_not_of (separators, stop+1);
}
}
bool isLeapYear (unsigned int year)
{
return !(year % 1000 && year % 100 && year % 4);
}
// Illustrate use of the find function.
void find_test () {
std::cout << "Test of algorithm find\n";
const int vintageYears[] = { 1967, 1972, 1974, 1980, 1995 };
const int* start = vintageYears;
const int* stop = vintageYears
+ sizeof vintageYears / sizeof *vintageYears;
const int* where = std::find_if (start, stop, isLeapYear);
if (where != stop)
std::cout << "first vintage leap year is " << *where << '\n';
else
std::cout << "no vintage leap years" << '\n';
where = std::find (start, stop, 1995);
if (where != stop)
std::cout << "1995 is position " << where - start
<< " in sequence" << '\n';
else
std::cout << "1995 does not occur in sequence\n";
}
void find_adjacent_test () {
std::cout << "Test of algorithm find adjacent\n";
const char text[] = "The bookkeeper carefully opened the door";
const char* start = text;
const char* stop = text + sizeof text;
const char* where = start;
std::cout << "In the text " << text << '\n';
while ((where = std::adjacent_find (where, stop)) != stop) {
std::cout << "double " << *where << " in position "
<< where-start << '\n';
++where;
}
}
// Illustrate the use of the search function.
void search_test () {
std::cout << "Test of algorithm search\n";
char base[] = "aspirations";
char text[] = "ration";
const char* const where = std::search (base, base+std::strlen (base),
text, text+std::strlen (text));
if (*where != '\0')
std::cout << "substring begins in position "
<< where - base << '\n';
else
std::cout << "substring does not occur in text\n";
}
// Illustrate use of max_element and min_element algorithms.
void max_min_example () {
std::cout << "Test of max and min algorithms \n";
// make a std::vector of "random" numbers between 0 and 99.
const int rn[] = {
83, 86, 77, 15, 93, 35, 86, 92, 49, 21,
62, 27, 90, 59, 63, 26, 40, 26, 72, 36,
11, 68, 67, 29, 82
};
std::vector<int, std::allocator<int> >
numbers (rn, rn + (sizeof rn/sizeof *rn));
// Print the maximum and minimum.
std::vector<int, std::allocator<int> >::iterator max =
std::max_element (numbers.begin (), numbers.end ());
std::cout << "largest value was " << *max << '\n';
std::vector<int, std::allocator<int> >::iterator min =
std::min_element (numbers.begin (), numbers.end ());
std::cout << "smallest value was " << *min << '\n';
// Example using std::strings.
std::string text = "it was the best of times, "\
"it was the worst of times.";
std::list<std::string, std::allocator<std::string> >words;
split (text, " ., !:;", words);
std::cout << "The smallest word is "
<< * std::min_element (words.begin (), words.end ())
<< " and the largest word is "
<< * std::max_element (words.begin (), words.end ())
<< '\n';
}
// Illustrate the use of the mismatch function.
void mismatch_test (const char * a, const char * b)
{
std::pair<const char *, const char *> differPositions (0, 0);
const char *aDiffPos;
const char *bDiffPos;
if (std::strlen (a) < std::strlen (b)) {
differPositions = std::mismatch (a, a + std::strlen (a), b);
aDiffPos = differPositions.first;
bDiffPos = differPositions.second;
}
else {
differPositions = std::mismatch (b, b + std::strlen (b), a);
aDiffPos = differPositions.second;
bDiffPos = differPositions.first;
}
std::cout << "string " << a;
if (*aDiffPos == *bDiffPos)
std::cout << " is equal to ";
else if (*aDiffPos < *bDiffPos)
std::cout << " is less than ";
else
std::cout << " is greater than ";
std::cout << b << '\n';
}
int main ()
{
std::cout << "STL generic algorithms -- Searching Algorithms\n";
find_test ();
find_adjacent_test ();
search_test ();
max_min_example ();
mismatch_test ("goody", "goody");
mismatch_test ("good", "goody");
mismatch_test ("goody", "good");
mismatch_test ("good", "fred");
mismatch_test ("fred", "good");
std::cout << "End of search algorithms test program\n";
return 0;
}

View File

@@ -0,0 +1,363 @@
/**************************************************************************
*
* alg3.cpp - Sample programs for STL generic algorihtms that modify
* their arguments in place.
*
* $Id: alg3.cpp 550991 2007-06-26 23:58:07Z sebor $
*
***************************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* Copyright 1994-2006 Rogue Wave Software.
*
**************************************************************************/
#include <algorithm> // for copy(), find(), generate(), ...
#include <functional> // for greater
#include <iostream> // for cout
#include <iterator> // for ostream_iterator
#include <list> // for list
#include <string> // for string
#include <vector> // for vector
#include <ctype.h>
#include <cstring>
#include <examples.h>
typedef std::ostream_iterator<int, char, std::char_traits<char> >
ostrm_iter_type;
struct iotaGenerator
{
iotaGenerator (int iv): current (iv) { }
int operator () () {
return current++;
}
private:
int current;
};
struct RandomInteger
{
static long seq [16];
long operator () (long n) const {
std::random_shuffle (seq, seq + sizeof seq / sizeof *seq);
const long rnd =
(seq [0] << 11) | (seq [1] << 8) | (seq [2] << 4) + seq [3];
return rnd % n;
}
};
long RandomInteger::seq [16] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf
};
bool isEven (int n)
{
return 0 == (n % 2);
}
// Illustrate the use of the reverse function.
void reverse_example ()
{
std::cout << "Illustrate std::reverse() algorithm\n";
// Example 1, reversing a std::string.
char text[] = "<Rats live on no evil star>";
std::cout << text << '\n';
std::reverse (text, text + sizeof text - 1);
std::cout << text << '\n';
// Example 2, reversing a std::list.
std::list<int, std::allocator<int> > iList;
std::generate_n (std::inserter (iList, iList.begin ()),
10, iotaGenerator (2));
std::copy (iList.begin (), iList.end (),
ostrm_iter_type (std::cout, " "));
std::cout << '\n';
std::reverse (iList.begin (), iList.end ());
std::copy (iList.begin (), iList.end (),
ostrm_iter_type (std::cout, " "));
std::cout << '\n';
}
// Illustrate the use of the replace function.
void replace_example ()
{
std::cout << "Illustrate std::replace() algorithm\n";
// Make std::vector 0 1 2 3 4.
std::vector<int, std::allocator<int> > numbers (11);
for (std::size_t i = 0; i < numbers.size (); i++)
numbers [i] = int (i < 5U ? i : 10U - i);
std::copy (numbers.begin (), numbers.end (),
ostrm_iter_type (std::cout, " "));
std::cout << '\n';
// Replace 0 by 2.
std::replace (numbers.begin (), numbers.end (), 3, 7);
std::copy (numbers.begin (), numbers.end (),
ostrm_iter_type (std::cout, " "));
std::cout << '\n';
// Replace even numbers by 9.
std::replace_if (numbers.begin (),
numbers.end (), isEven, 9);
std::copy (numbers.begin (), numbers.end (),
ostrm_iter_type (std::cout, " "));
std::cout << '\n';
// Copy into a std::list, replastd::cing 9 by 3.
int aList[] = { 2, 1, 4, 3, 2, 5 };
int bList[6];
int cList[6];
std::replace_copy (aList, aList+6, &bList[0], 2, 7);
std::replace_copy_if (bList, bList+6, &cList[0],
std::bind2nd (std::greater<int> (), 3), 8);
std::copy (bList, bList + 6, ostrm_iter_type (std::cout, " "));
std::cout << '\n';
std::copy (cList, cList + 6, ostrm_iter_type (std::cout, " "));
std::cout << '\n';
}
// Illustrate the use of the rotate function.
void rotate_example ()
{
std::cout << "Illustrate std::rotate() algorithm\n";
// Create the std::list 1 2 3 ... 10
std::list<int, std::allocator<int> > iList;
std::generate_n (std::inserter (iList, iList.begin ()),
10, iotaGenerator (1));
// Find the location of the seven.
std::list<int, std::allocator<int> >::iterator
middle = std::find (iList.begin (), iList.end (), 7);
// Now rotate around that location.
std::rotate (iList.begin (), middle, iList.end ());
std::copy (iList.begin (), iList.end (),
ostrm_iter_type (std::cout, " "));
std::cout << '\n';
// Rotate again around the same location.
std::list<int, std::allocator<int> > cList;
std::rotate_copy (iList.begin (), middle, iList.end (),
std::inserter (cList, cList.begin ()));
std::copy (cList.begin (), cList.end (),
ostrm_iter_type (std::cout, " "));
std::cout << '\n';
}
// Illustrate the use of the paration function.
void partition_example ()
{
std::cout << "Illustrate std::partition() algorithm\n";
// First make the std::vector 1 2 3 ... 10.
std::vector<int, std::allocator<int> > numbers (10);
std::generate (numbers.begin (),
numbers.end (), iotaGenerator (1));
// Now put the odd values low, even values high.
std::vector<int, std::allocator<int> >::iterator
result = std::partition (numbers.begin (), numbers.end (),
isEven);
std::copy (numbers.begin (), numbers.end (),
ostrm_iter_type (std::cout, " "));
std::cout << "\nmiddle location " << result - numbers.begin () << '\n';
// Now do a stable partition.
std::generate (numbers.begin (),
numbers.end (), iotaGenerator (1));
std::copy (numbers.begin (), numbers.end (),
ostrm_iter_type (std::cout, " "));
std::cout << '\n';
}
bool nameCompare (const char *a, const char *b)
{
return std::strcmp (a, b) <= 0;
}
// Illustrate the use of the next_permutation function.
void permutation_example ()
{
std::cout << "Illustrate std::next_permutation() algorithm\n";
// Start with the values 1 2 3 in sequence.
int start [] = { 1, 2, 3 };
do {
std::copy (start, start + 3, ostrm_iter_type (std::cout, " "));
std::cout << '\n';
} while (std::next_permutation (start, start + 3));
const char alpha[] = "Alpha";
const char beta[] = "Beta";
const char gamma[] = "Gamma";
const char* names[] = { alpha, beta, gamma };
typedef std::ostream_iterator<const char*, char, std::char_traits<char> >
Iter;
do {
std::copy (names, names + 3, Iter (std::cout, " "));
std::cout << '\n';
} while (std::next_permutation (names, names + 3, nameCompare));
std::cout << "Illustrate std::prev_permutation() algorithm\n";
char word[] = "bela";
do
std::cout << word << ' ';
while (std::prev_permutation (word, &word[4]));
std::cout << '\n';
}
// Illustrate the use of the inplace_merge function.
void inplace_merge_example ()
{
std::cout << "Illustrate std::inplace_merge() algorithm\n";
// First generate the numbers 0 2 4 6 8 1 3 5 7 9.
std::vector<int, std::allocator<int> > numbers (10);
for (std::size_t i = 0; i < numbers.size (); i++)
numbers [i] = int (i < 5U ? 2U * i : 2U * (i - 5U) + 1U);
std::copy (numbers.begin (), numbers.end (),
ostrm_iter_type (std::cout, " "));
std::cout << '\n';
std::vector<int, std::allocator<int> >::iterator
midvec = std::find (numbers.begin (), numbers.end (), 1);
// Copy them into a std::list.
std::list<int, std::allocator<int> > numList;
std::copy (numbers.begin (), numbers.end (),
std::inserter (numList, numList.begin ()));
std::list<int, std::allocator<int> >::iterator
midList = std::find (numList.begin (), numList.end (), 1);
std::copy (numList.begin (), numList.end (),
ostrm_iter_type (std::cout, " "));
std::cout << '\n';
// Now put them back together.
std::inplace_merge (numbers.begin (), midvec, numbers.end ());
std::inplace_merge (numList.begin (), midList, numList.end ());
std::copy (numList.begin (), numList.end (),
ostrm_iter_type (std::cout, " "));
std::cout << '\n';
}
// Illustrate the use of the random_shuffle function.
void random_shuffle_example ()
{
std::cout << "Illustrate std::generate() algorithm\n";
// First make the std::vector 1 2 3 ... 10.
std::vector<int, std::allocator<int> > numbers (10);
std::generate (numbers.begin (),
numbers.end (), iotaGenerator (1));
std::copy (numbers.begin (), numbers.end (),
ostrm_iter_type (std::cout, " "));
std::cout << "\nIllustrate std::random_shuffle() algorithm\n";
// Randomly shuffle the elements.
RandomInteger rnd;
std::random_shuffle (numbers.begin (), numbers.end (), rnd);
std::copy (numbers.begin (), numbers.end (),
ostrm_iter_type (std::cout, " "));
std::cout << '\n';
// Do it again.
std::random_shuffle (numbers.begin (), numbers.end (), rnd);
std::copy (numbers.begin (), numbers.end (),
ostrm_iter_type (std::cout, " "));
std::cout << '\n';
}
int main ()
{
std::cout << "STL generic algorithms -- in-place algorithms\n";
reverse_example ();
replace_example ();
rotate_example ();
partition_example ();
permutation_example ();
inplace_merge_example ();
random_shuffle_example ();
std::cout << "End of in-place algorithm sample program\n";
return 0;
}

View File

@@ -0,0 +1,162 @@
/**************************************************************************
*
* alg4.cpp - Example programs for STL generic algorithms removal
* algorithms.
*
* $Id: alg4.cpp 550991 2007-06-26 23:58:07Z sebor $
*
***************************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* Copyright 1994-2006 Rogue Wave Software.
*
**************************************************************************/
#include <list>
#include <set>
#include <algorithm>
#include <iostream>
#include <iterator>
#include <examples.h>
typedef std::ostream_iterator<int, char, std::char_traits<char> >
ostrm_iter_type;
bool isEven (int n) {
return 0 == (n % 2);
}
// Illustrate the use of the remove algorithm.
void remove_example ()
{
std::cout << "Remove Algorithm examples" << std::endl;
// Create a list of numbers.
int data[] = { 1, 2, 4, 3, 1, 4, 2 };
std::list<int, std::allocator<int> > aList;
std::copy (data, data+7, std::inserter (aList, aList.begin ()));
std::cout << "Original list: ";
std::copy (aList.begin (), aList.end (),
ostrm_iter_type (std::cout, " "));
std::cout << std::endl;
// Remove 2's, copy into a new list.
std::list<int, std::allocator<int> > newList;
std::remove_copy (aList.begin (), aList.end (),
std::back_inserter (newList), 2);
std::cout << "After removing 2's: ";
std::copy (newList.begin (), newList.end (),
ostrm_iter_type (std::cout, " "));
std::cout << std::endl;
// Remove 2's in place.
std::list<int, std::allocator<int> >::iterator
where = std::remove (aList.begin (), aList.end (), 2);
std::cout << "List after removal, before erase: ";
std::copy (aList.begin (), aList.end (),
ostrm_iter_type (std::cout, " "));
std::cout << std::endl;
aList.erase (where, aList.end ());
std::cout << "List after erase: ";
std::copy (aList.begin (), aList.end (),
ostrm_iter_type (std::cout, " "));
std::cout << std::endl;
// Remove all even values.
where = std::remove_if (aList.begin (), aList.end (), isEven);
aList.erase (where, aList.end ());
std::cout << "List after removing even values: ";
std::copy (aList.begin (), aList.end (),
ostrm_iter_type (std::cout, " "));
std::cout << std::endl;
}
// Illustrate use of the unqiue algorithm.
void unique_example ()
{
// First make a list of values.
int data[] = { 1, 3, 3, 2, 2, 4 };
std::list<int, std::allocator<int> > aList;
std::copy (data, data+6, std::inserter (aList, aList.begin ()));
std::cout << "Origianal List: ";
std::copy (aList.begin (), aList.end (),
ostrm_iter_type (std::cout, " "));
std::cout << std::endl;
// Copy unique elements into a set.
std::set<int, std::less<int>, std::allocator<int> > aSet;
std::unique_copy (aList.begin (), aList.end (),
std::inserter (aSet, aSet.begin ()));
std::cout << "Set after unique_copy: ";
std::copy (aSet.begin (), aSet.end (), ostrm_iter_type (std::cout, " "));
std::cout << std::endl;
// Copy unique elements in place.
std::list<int, std::allocator<int> >::iterator
where = std::unique (aList.begin (), aList.end ());
std::cout << "List after calling unique: ";
std::copy (aList.begin (), aList.end (),
ostrm_iter_type (std::cout, " "));
std::cout << std::endl;
// Remove trailing values.
aList.erase (where, aList.end ());
std::cout << "List after erase: ";
std::copy (aList.begin (), aList.end (),
ostrm_iter_type (std::cout, " "));
std::cout << std::endl;
}
int main ()
{
std::cout << "STL generic algorithms -- Removal Algorithms"
<< std::endl;
remove_example ();
unique_example ();
std::cout << "End of removal algorithms sample program"
<< std::endl;
return 0;
}

View File

@@ -0,0 +1,199 @@
/**************************************************************************
*
* alg5.cpp - Example programs for STL generic algorithms those
* producing scalar values.
*
* $Id: alg5.cpp 550991 2007-06-26 23:58:07Z sebor $
*
***************************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* Copyright 1994-2006 Rogue Wave Software.
*
**************************************************************************/
#include <algorithm> // for copy
#include <functional> // for multiplies
#include <iterator> // for ostream_iterator
#include <list> // for list
#include <numeric> // for accumulate
#include <iostream> // for cout, endl
#include <examples.h>
typedef std::ostream_iterator<int, char, std::char_traits<char> >
ostrm_iter_type;
// Forward declarations.
bool isVowel (char);
void count_example ();
void accumulate_example ();
void inner_product_example ();
void equal_example ();
bool isVowel (char c) {
switch (c)
{
case 'a': case 'A':
case 'e': case 'E':
case 'i': case 'I':
case 'o': case 'O':
case 'u': case 'U':
return true;
}
return false;
}
// Illustrate the use of the count function.
void count_example () {
int ecount = 0;
int vowelCount = 0;
char text[] = "Now is the time to begin";
#ifdef _RWSTD_STRICT_ANSI
ecount = std::count (text, text + sizeof text, 'e');
vowelCount = std::count_if (text, text + sizeof text, isVowel);
#else
std::count (text, text + sizeof text, 'e', ecount);
std::count_if (text, text + sizeof text, isVowel, vowelCount);
#endif // _RWSTD_STRICT_ANSI
std::cout << "There are " << ecount
<< " letter e's " << std::endl
<< "and " << vowelCount
<< " vowels in the text:" << text
<< std::endl;
}
// Add n to 1 to std::list.
std::list<int, std::allocator<int> >&
intReplicate (std::list<int, std::allocator<int> >& nums, int n) {
while (n)
nums.push_back (n--);
return nums;
}
// Illustrate the use of the accumulate function.
void accumulate_example () {
int numbers[] = { 1, 2, 3, 4, 5 };
int sum = std::accumulate (numbers, numbers+5, 0);
int product = std::accumulate (numbers,
numbers+5, 1, std::multiplies<int> ());
std::cout << "The sum of the first five numbers is "
<< sum
<< std::endl;
std::cout << "The product of the first five numbers is "
<< product
<< std::endl;
// Example with different types for init.
std::list<int, std::allocator<int> > nums;
nums = std::accumulate (numbers, numbers+5, nums, intReplicate);
std::copy (nums.begin (), nums.end (), ostrm_iter_type (std::cout, " "));
std::cout << std::endl;
}
// Illustrate the use of the inner_product function.
void inner_product_example () {
int a[] = { 4, 3, -2 };
int b[] = { 7, 3, 2 };
// Example 1, simple inner product.
int in1 = std::inner_product (a, a+3, b, 0);
std::cout << "Inner product is " << in1 << std::endl;
// Example 2, using different operations.
bool anyequal = std::inner_product (a, a+3, b, true,
std::logical_or<bool> (),
std::equal_to<int> ());
std::cout << "any equal? " << anyequal << std::endl;
}
// Illustrate the use of the equal function.
void equal_example () {
int a[] = { 4, 5, 3 };
int b[] = { 4, 3, 3 };
int c[] = { 4, 5, 3 };
std::cout << "a = b is:" << std::equal (a, a+3, b) << std::endl;
std::cout << "a = c is:" << std::equal (a, a+3, c) << std::endl;
std::cout << "a pair-wise-greater_equal b is"
<< std::equal (a, a+3, b, std::greater_equal<int> ())
<< std::endl;
}
// Illustrate the use of the lexical_comparison function.
void lexical_comparison_example () {
char wordOne[] = "everything";
char wordTwo[] = "everybody";
std::cout << "compare everybody to everything "
<< std::lexicographical_compare (wordTwo,
wordTwo + sizeof wordTwo,
wordOne,
wordOne + sizeof wordOne)
<< std::endl;
int a[] = { 3, 4, 5, 2 };
int b[] = { 3, 4, 5 };
int c[] = { 3, 5 };
std::cout << "compare a to b: "
<< std::lexicographical_compare (a, a+4, b, b+3) << std::endl;
std::cout << "compare a to c: "
<< std::lexicographical_compare (a, a+4, c, c+2) << std::endl;
}
int main () {
std::cout << "STL generic algorithms -- "\
<< "algorithms that produce scalar results" << std::endl;
count_example ();
accumulate_example ();
inner_product_example ();
equal_example ();
lexical_comparison_example ();
std::cout << "End of scalar algorithms test" << std::endl;
return 0;
}

View File

@@ -0,0 +1,167 @@
/**************************************************************************
*
* alg6.cpp - STL generic algorithms that produce new sequences.
*
* $Id: alg6.cpp 550991 2007-06-26 23:58:07Z sebor $
*
***************************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* Copyright 1994-2006 Rogue Wave Software.
*
**************************************************************************/
#include <vector>
#include <list>
#include <functional>
#include <algorithm>
#include <numeric>
#include <iostream>
#include <iterator>
#include <functional>
#include <examples.h>
typedef std::ostream_iterator<int, char, std::char_traits<char> > ostrm_iter_type;
int square (int n) {
return n * n;
}
class iotaGen {
public:
iotaGen (int iv) : current (iv)
{ }
int operator () () {
return current++;
}
private:
int current;
};
// Illustrate the use of the transform algorithm.
void transform_example () {
// Generate a std::list of values from 1 to 6.
std::list<int, std::allocator<int> > aList;
std::generate_n (std::inserter (aList, aList.begin ()), 6, iotaGen (1));
std::cout << "Original list: ";
std::copy (aList.begin (), aList.end (), ostrm_iter_type (std::cout, " "));
std::cout << std::endl;
// Transform elements by squaring, copy into std::vector.
std::vector<int, std::allocator<int> > aVec (6);
std::transform (aList.begin (), aList.end (), aVec.begin (), square);
std::cout << "After squaring: ";
std::copy (aVec.begin (), aVec.end (), ostrm_iter_type (std::cout, " "));
std::cout << std::endl;
// Transform std::vector again, in place, yielding 4th powers.
std::transform (aVec.begin (), aVec.end (), aVec.begin (), square);
std::cout << "After squaring again: ";
std::copy (aVec.begin (), aVec.end (),ostrm_iter_type (std::cout, " "));
std::cout << std::endl;
// Transform in parallel, yielding cubes.
std::vector<int, std::allocator<int> > cubes (6);
std::transform (aVec.begin (), aVec.end (), aList.begin (), cubes.begin (),
std::divides<int> ());
std::cout << "After division: ";
std::copy (cubes.begin (), cubes.end (), ostrm_iter_type (std::cout, " "));
std::cout << std::endl;
}
// Illustrate the use of the partial sum algorithm.
void partial_sum_example () {
// Generate values 1 to 5.
std::vector<int, std::allocator<int> > aVec (5);
std::generate (aVec.begin (), aVec.end (), iotaGen (1));
// Output partial sums.
std::cout << "Partial sums examples" << std::endl;
std::cout << "Partial sums : ";
std::partial_sum (aVec.begin (), aVec.end (),
ostrm_iter_type (std::cout, " "));
std::cout << std::endl;
// Output partial products.
std::cout << "Partial products: ";
std::partial_sum (aVec.begin (), aVec.end (),
ostrm_iter_type (std::cout, " "), std::multiplies<int> () );
std::cout << std::endl;
}
// Illustrate the use of the adjacent difference algorithm.
void adjacent_difference_example () {
// Generate values 1 to 5.
std::vector<int, std::allocator<int> > aVec (5);
std::generate (aVec.begin (), aVec.end (), iotaGen (1));
// Output partial sums.
std::cout << "Adjacent Differences examples" << std::endl;
std::cout << "Adjacent Differences : ";
std::adjacent_difference
(aVec.begin (), aVec.end (), ostrm_iter_type (std::cout, " "));
std::cout << std::endl;
// Output partial products.
std::cout << "Adjacent sums: ";
std::adjacent_difference (aVec.begin (), aVec.end (),
ostrm_iter_type (std::cout, " "),
std::plus<int> ());
std::cout << std::endl;
}
int main () {
std::cout << "STL generic algorithms -- that transform sequences"
<< std::endl;
transform_example ();
partial_sum_example ();
adjacent_difference_example ();
std::cout << "End generic transform algorithms example" << std::endl;
return 0;
}

View File

@@ -0,0 +1,306 @@
/**************************************************************************
*
* alg7.cpp - Illustrate the use of the sort related generic algorithms.
*
* $Id: alg7.cpp 636370 2008-03-12 15:32:56Z faridz $
*
***************************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* Copyright 1994-2008 Rogue Wave Software, Inc.
*
**************************************************************************/
#include <rw/_config.h>
#if defined (__IBMCPP__) && !defined (_RWSTD_NO_IMPLICIT_INCLUSION)
// Disable implicit inclusion to work around
// a limitation in IBM's VisualAge 5.0.2.0 (see PR#26959)
# define _RWSTD_NO_IMPLICIT_INCLUSION
#endif
#include <vector>
#include <deque>
#include <list>
#include <algorithm>
#include <functional>
#include <iostream>
#include <iterator>
#include <examples.h>
// returns a random integer in the range [0, 100)
int randomValue ()
{
static int digits[] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
};
std::random_shuffle (digits, digits + sizeof digits / sizeof *digits);
const int rnd = digits [0] * 10 + digits [1];
return rnd;
}
typedef std::ostream_iterator<int, char, std::char_traits<char> > Iter;
void sortExample ()
{
std::cout << "Sort algorithms\n";
Iter intOut (std::cout, " ");
// Fill both a std::vector and a std::deque with random integers.
std::vector<int, std::allocator<int> > aVec (15);
std::deque<int, std::allocator<int> > aDec (15);
std::generate (aVec.begin (), aVec.end (), randomValue);
std::generate (aDec.begin (), aDec.end (), randomValue);
// Sort the std::vector ascending.
std::sort (aVec.begin (), aVec.end ());
std::copy (aVec.begin (), aVec.end (), intOut);
std::cout << '\n';
// Sort the std::deque descending.
std::sort (aDec.begin (), aDec.end (), std::greater<int>() );
std::copy (aDec.begin (), aDec.end (), intOut);
std::cout << '\n';
// Sort the std::vector descending?
std::sort (aVec.rbegin (), aVec.rend ());
std::copy (aVec.begin (), aVec.end (), intOut);
std::cout << '\n';
}
void partial_sort_example ()
{
std::cout << "Partial sort examples\n";
Iter intOut (std::cout, " ");
// Make a std::vector of 15 random integers.
std::vector<int, std::allocator<int> > aVec (15);
std::generate (aVec.begin (), aVec.end (), randomValue);
std::copy (aVec.begin (), aVec.end (), intOut);
std::cout << '\n';
// Partial sort the first seven positions.
std::partial_sort (aVec.begin (), aVec.begin () + 7, aVec.end ());
std::copy (aVec.begin (), aVec.end (), intOut);
std::cout << '\n';
// Make a std::list of random integers.
std::list<int, std::allocator<int> > aList (15);
std::generate (aList.begin (), aList.end (), randomValue);
std::copy (aList.begin (), aList.end (), intOut);
std::cout << '\n';
// Sort only the first seven elements.
std::vector<int, std::allocator<int> > start (7);
std::partial_sort_copy (aList.begin (), aList.end (),
start.begin (), start.end (), std::greater<int>());
std::copy (start.begin (), start.end (), intOut);
std::cout << '\n';
}
// Illustrate the use of the nth_largest function.
void nth_element_example ()
{
std::cout << "Nth largest example\n";
// Make a std::vector of random integers.
std::vector<int, std::allocator<int> > aVec (10);
std::generate (aVec.begin (), aVec.end (), randomValue);
Iter intOut (std::cout, " ");
// Now find the 5th largest.
std::vector<int, std::allocator<int> >::iterator nth = aVec.begin () + 4;
std::nth_element (aVec.begin (), nth, aVec.end ());
std::cout << "fifth largest is " << *nth << " in\n";
std::copy (aVec.begin (), aVec.end (), intOut);
std::cout << '\n';
}
// Illustrate the use of the binary search functions.
void binary_search_example ()
{
std::cout << "Binary search example\n";
Iter intOut (std::cout, " ");
// Make an ordered std::vector of 15 random integers.
std::vector<int, std::allocator<int> > aVec (15);
std::generate (aVec.begin (), aVec.end (), randomValue);
std::sort (aVec.begin (), aVec.end ());
std::copy (aVec.begin (), aVec.end (), intOut), std::cout << '\n';
// See if it contains an eleven.
if (std::binary_search (aVec.begin (), aVec.end (), 11))
std::cout << "contains an 11\n";
else
std::cout << "does not contain an 11\n";
// Insert an 11 and a 14.
std::vector<int, std::allocator<int> >::iterator where;
where = std::lower_bound (aVec.begin (), aVec.end (), 11);
aVec.insert (where, 11);
where = std::upper_bound (aVec.begin (), aVec.end (), 14);
aVec.insert (where, 14);
std::copy (aVec.begin (), aVec.end (), intOut), std::cout << '\n';
}
// Illustrate the use of the merge function.
void merge_example ()
{
std::cout << "Merge algorithm examples\n";
// Make a std::list and std::vector of 10 random integers.
std::vector<int, std::allocator<int> > aVec (10);
std::list<int, std::allocator<int> > aList (10);
std::generate (aVec.begin (), aVec.end (), randomValue);
std::sort (aVec.begin (), aVec.end ());
std::generate_n (aList.begin (), 10, randomValue);
aList.sort ();
// Merge into a std::vector.
std::vector<int, std::allocator<int> > vResult (aVec.size () + aList.size ());
std::merge (aVec.begin (), aVec.end (), aList.begin (), aList.end (),
vResult.begin ());
// Merge into a std::list.
std::list<int, std::allocator<int> > lResult;
std::merge (aVec.begin (), aVec.end (), aList.begin (), aList.end (),
std::inserter (lResult, lResult.begin ()));
// Merge into the output.
std::merge (aVec.begin (), aVec.end (), aList.begin (), aList.end (),
Iter (std::cout, " "));
std::cout << '\n';
}
class iotaGen
{
public:
iotaGen (int c = 0) : current (c) { }
int operator () () { return current++; }
private:
int current;
};
// Illustrate the use of the generic set functions.
void set_example ()
{
std::cout << "Set operations:\n";
// Make a couple of ordered std::lists.
std::list <int, std::allocator<int> > listOne, listTwo;
std::generate_n (std::inserter (listOne, listOne.begin ()), 5, iotaGen (1));
std::generate_n (std::inserter (listTwo, listTwo.begin ()), 5, iotaGen (3));
Iter intOut (std::cout, " ");
// union - 1 2 3 4 5 6 7
std::set_union (listOne.begin (), listOne.end (),
listTwo.begin (), listTwo.end (), intOut);
std::cout << '\n';
// merge - 1 2 3 3 4 4 5 5 6 7
std::merge (listOne.begin (), listOne.end (),
listTwo.begin (), listTwo.end (), intOut);
std::cout << '\n';
// intersection 3 4 5
std::set_intersection (listOne.begin (), listOne.end (),
listTwo.begin (), listTwo.end (), intOut);
std::cout << '\n';
// difference 1 2
std::set_difference (listOne.begin (), listOne.end (),
listTwo.begin (), listTwo.end (), intOut);
std::cout << '\n';
// symmetric difference 1 2 6 7
std::set_symmetric_difference (listOne.begin (), listOne.end (),
listTwo.begin (), listTwo.end (),
intOut);
std::cout << '\n';
if (std::includes (listOne.begin (), listOne.end (),
listTwo.begin (), listTwo.end ()))
std::cout << "set is subset\n";
else
std::cout << "set is not subset\n";
}
// Illustrate the use of the heap functions.
void heap_example ()
{
Iter intOut (std::cout, " ");
// Make a heap of 15 random integers.
std::vector<int, std::allocator<int> > aVec (15);
std::generate (aVec.begin (), aVec.end (), randomValue);
std::make_heap (aVec.begin (), aVec.end ());
std::copy (aVec.begin (), aVec.end (), intOut);
std::cout << "\nLargest value " << aVec.front () << '\n';
// Remove largest and reheap.
std::pop_heap (aVec.begin (), aVec.end ());
aVec.pop_back ();
std::copy (aVec.begin (), aVec.end (), intOut);
std::cout << '\n';
// Add a 97 to the heap.
aVec.push_back (97);
std::push_heap (aVec.begin (), aVec.end ());
std::copy (aVec.begin (), aVec.end (), intOut);
std::cout << '\n';
// Finally, make into sorted collection.
std::sort_heap (aVec.begin (), aVec.end ());
std::copy (aVec.begin (), aVec.end (), intOut);
std::cout << '\n';
}
int main ()
{
std::cout << "Sorting generic algorithms examples\n";
sortExample ();
partial_sort_example ();
nth_element_example ();
binary_search_example ();
merge_example ();
set_example ();
heap_example ();
std::cout << "End sorting examples\n";
return 0;
}

View File

@@ -0,0 +1,106 @@
/**************************************************************************
*
* calc.cpp - RPN Calculator -- Illustration of the use of stacks.
*
* $Id: calc.cpp 550991 2007-06-26 23:58:07Z sebor $
*
***************************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* Copyright 1994-2006 Rogue Wave Software.
*
**************************************************************************/
#include <vector>
#include <stack>
#include <iostream>
#include <examples.h>
// Simulate the behavior of a simple integer calculator.
struct Calculator
{
int currentMemory () const {
return data_.top ();
}
void pushOperand (int value) {
data_.push (value);
}
void doOperator (char);
private:
std::stack<int, std::vector<int, std::allocator<int> > > data_;
};
void Calculator::doOperator (char theOp)
{
int tmp = data_.top ();
data_.pop ();
switch (theOp) {
case '+': tmp = data_.top () + tmp; break;
case '-': tmp = data_.top () - tmp; break;
case '*': tmp = data_.top () * tmp; break;
case '/': tmp = data_.top () / tmp; break;
case '%': tmp = data_.top () % tmp; break;
}
data_.pop ();
data_.push (tmp);
}
int main ()
{
std::cout << "Calculator example program, from Chapter 8\n"
<< "Enter a legal RPN expression, end with p q (print and quit)"
<< std::endl;
Calculator calc;
for (char c; std::cin >> c; ) {
int intval;
switch (c) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
std::cin.putback (c);
std::cin >> intval;
calc.pushOperand (intval);
break;
case '+': case '-': case '*': case '/': case '%':
calc.doOperator (c);
break;
case 'p':
std::cout << calc.currentMemory () << std::endl;
break;
case 'q':
std::cout << "End calculator program" << std::endl;
return 0; // quit program
}
}
return 0;
}

View File

@@ -0,0 +1,67 @@
/**************************************************************************
*
* complx.cpp - Complex Number example program.
*
* $Id: complx.cpp 550991 2007-06-26 23:58:07Z sebor $
*
***************************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* Copyright 1994-2006 Rogue Wave Software.
*
**************************************************************************/
#include <complex>
#include <utility>
#include <iostream>
#include <examples.h>
typedef std::complex<double> dcomplex;
// Return roots of a quadratic equation.
std::pair<dcomplex, dcomplex>
quadratic (dcomplex a, dcomplex b, dcomplex c) {
dcomplex root = std::sqrt(b * b - 4.0 * a * c);
a = a * 2.0;
return std::make_pair ((-b + root) / a, (-b - root) / a);
}
int main () {
dcomplex a(2, 3);
dcomplex b(4, 5);
dcomplex c(6, 7);
std::pair<dcomplex, dcomplex> ans = quadratic(a, b, c);
std::cout << "Roots are " << ans.first << " and "
<< ans.second << std::endl;
return 0;
}

View File

@@ -0,0 +1,141 @@
/**************************************************************************
*
* concord.cpp - Concordance sample program.
*
* $Id: concord.cpp 550991 2007-06-26 23:58:07Z sebor $
*
***************************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* Copyright 1994-2006 Rogue Wave Software.
*
**************************************************************************/
#include <iostream>
#include <list>
#include <locale>
#include <map>
#include <string>
#include <examples.h>
// Split a line of text into words.
void split (const std::string& text, const std::string& separators,
std::list<std::string,std::allocator<std::string> > &words)
{
const std::string::size_type n = text.length ();
std::string::size_type start = text.find_first_not_of (separators);
while (start < n) {
std::string::size_type stop = text.find_first_of (separators, start);
if (stop > n) stop = n;
words.push_back (text.substr (start, stop-start));
start = text.find_first_not_of (separators, stop+1);
}
}
class concordance
{
typedef std::multimap<std::string,int,
std::less<std::string>,
std::allocator<std::pair<const std::string,
int> > > wordDictType;
public:
void addWord (std::string, int);
void readText (std::istream &);
void printConcordance (std::ostream &);
private:
wordDictType wordMap;
};
void concordance::addWord (std::string word, int line)
{
// First get range of entries with same key.
wordDictType::iterator low = wordMap.lower_bound (word);
wordDictType::iterator high = wordMap.upper_bound (word);
// Loop over entires, see if any match current line.
for ( ; low != high; ++low)
if ( (*low).second == line)
return;
// Didn't occur, add now.
wordMap.insert (wordDictType::value_type (word, line));
}
void allLower (std::string &s)
{
for (std::size_t i = 0; i < s.size (); i++)
if ((std::isupper)(s [i], std::locale ()))
s [i] = (std::tolower)(s [i], std::locale ());
}
void concordance::readText (std::istream & in)
{
std::string line;
for (int i = 1; std::getline (in, line); i++) {
allLower (line);
std::list<std::string, std::allocator<std::string> > words;
split (line, " , .;:", words);
std::list<std::string, std::allocator<std::string> >::iterator wptr;
for (wptr = words.begin (); wptr != words.end (); ++wptr)
addWord (*wptr, i);
}
}
void concordance::printConcordance (std::ostream & out)
{
std::string lastword ("");
wordDictType::iterator pairPtr;
wordDictType::iterator stop = wordMap.end ();
for (pairPtr = wordMap.begin (); pairPtr != stop; ++pairPtr)
// If word is same as previous, just print line number.
if (lastword == (*pairPtr).first)
out << ' ' << (*pairPtr).second;
else {
// First entry of word.
lastword = (*pairPtr).first;
std::cout << '\n' << lastword << ": " << (*pairPtr).second;
}
std::cout << '\n';
}
int main ()
{
std::cout << "Concordance sample program, from Chapter 7\n"
<< "Enter text, then end-of-file:\n";
concordance words;
words.readText (std::cin);
words.printConcordance (std::cout);
std::cout << "End of concordance sample program\n";
return 0;
}

View File

@@ -0,0 +1,257 @@
/**************************************************************************
*
* dynatype.cpp - Example program of map. See Class Reference Section
*
* $Id: dynatype.cpp 611273 2008-01-11 19:33:02Z vitek $
*
***************************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* Copyright 2001-2005, 2007 Rogue Wave Software, Inc.
*
**************************************************************************/
#include <iostream>
#include <map>
#include <typeinfo>
#include <examples.h>
// ordinary class whose objects are dynamically typed at runtime
class dynatype
{
// member template class that encapsulates a per-specialization copy
// of an associative container (map) used to bind a specific instance
// of dynatype to its value
template <class T>
struct map {
typedef std::map<const dynatype*, T> map_type;
static map_type& get ();
};
// helper: removes this instance of dynatype from map
template <class T>
void remove () {
map<T>::get ().erase (this);
}
// helper: copies one instance of dynatype to another
template <class T>
void copy (const dynatype &rhs) {
// cast to <const T&> instead of <T> to avoid error on gcc 3.4.4/cygwin:
// error: invalid static_cast from type `const dynatype' to type `int'
*this = static_cast<const T&>(rhs);
}
// pointers to the helpers (do not depend on a template parameter)
void (dynatype::*p_remove)();
void (dynatype::*p_copy)(const dynatype&);
// provides access to the mapped data value or throws bad_cast
template <class T>
T& retrieve (const T*) {
if (map<T>::get ().end () == map<T>::get ().find (this))
throw std::bad_cast ();
return map<T>::get () [this];
}
// overload throws away const on template parameter
template <class T>
T& retrieve (const T*) const {
return const_cast<dynatype*>(this)->retrieve ((T*)0);
}
public:
dynatype ();
// construct a dynatype object from a value of any type
template <class T>
dynatype (const T&);
// copy one dynatype object to another
dynatype (const dynatype &rhs)
: p_remove (rhs.p_remove),
p_copy (rhs.p_copy) {
(this->*p_copy)(rhs);
}
// assign one dynatype object to another
dynatype& operator= (const dynatype &rhs);
// remove `this' from the map destroy the object
~dynatype () {
(this->*p_remove)();
}
// retrieve a reference to the concrete type from an instance of
// dynatype throws std::bad_cast if the types don't match exactly
template <class T>
operator T& () {
return retrieve ((T*)0);
}
// retrieve a const reference to the concrete type from an instance of
// dynatype throws std::bad_cast if the types don't match exactly
template <class T>
operator const T& () const {
return retrieve ((T*)0);
}
// assign a value of any type to an instance of dynatype
template <class T>
dynatype& operator= (const T &t);
};
// 14.7.3, p6 - explicit specializations must be defined before first use
template <>
void dynatype::
remove<void> ()
{ /* no-op */ }
template <>
void dynatype::
copy<void> (const dynatype&)
{ /* no-op */ }
// initialize with pointers to no-ops
dynatype::
dynatype ()
: p_remove (&dynatype::remove<void>),
p_copy (&dynatype::copy<void>)
{
}
template <class T>
typename dynatype::map<T>::map_type&
dynatype::map<T>::
get ()
{
static map_type m;
return m;
}
// construct a dynatype object from a value of any type
template <class T>
dynatype::
dynatype (const T &t)
: p_remove (&dynatype::remove<T>),
p_copy (&dynatype::copy<T>)
{
*this = t;
}
// assign one dynatype object to another
dynatype& dynatype::
operator= (const dynatype &rhs)
{
if (this != &rhs) {
// remove `this' from the associated map
(this->*p_remove)();
// copy pointers to helpers from the right-hand-side
p_remove = rhs.p_remove;
p_copy = rhs.p_copy;
// copy value of unknown type from rhs to `*this'
(this->*p_copy)(rhs);
}
return *this;
}
// assign a value of any type to an instance of dynatype
template <class T>
dynatype& dynatype::
operator= (const T &t)
{
// remove `this' from the map of the corresponding type
(this->*p_remove)();
// insert `t' into the map specialized on `T'
map<T>::get () [this] = t;
// assign pointers to the helpers
p_remove = &dynatype::remove<T>;
p_copy = &dynatype::copy<T>;
return *this;
}
int main ()
{
try {
// create an instance of dynatype an initialized it with an int
dynatype v1 = 1;
std::cout << "static_cast<const int&>(v1 = 1) = ";
std::cout << static_cast<const int&>(v1) << '\n';
// assign a double to an instance of dynatype
v1 = 3.14;
std::cout << "static_cast<const double&>(v1 = 3.14) = ";
std::cout << static_cast<const double&>(v1) << '\n';
// copy construct an instance of dynatype
dynatype v2 = v1;
std::cout << "static_cast<const double&>(v2 = v1) = ";
std::cout << static_cast<const double&>(v2) << '\n';
// assign a const char* literal to an instance of dynatype
const char* const literal = "abc";
v2 = literal;
std::cout << "static_cast<const char* const&>(v2 = \"abc\") = ";
std::cout << static_cast<const char* const&>(v2) << '\n';
// assign one instance of dynatype to another
v1 = v2;
std::cout << "static_cast<const char* const&>(v1 = v2) = ";
std::cout << static_cast<const char* const&>(v1) << '\n';
// create uninitialized (untyped) instances of dynatype
dynatype v3, v4;
// assign one uninitialized instance to another
v3 = v4;
// attempt to extract any value from an unitialized dynatype fails
std::cout << "static_cast<const char&>(v3) = ";
std::cout << static_cast<const char&>(v3) << '\n';
}
catch (...) {
std::cerr << "exception\n";
}
return 0;
}

View File

@@ -0,0 +1,138 @@
/**************************************************************************
*
* graph.cpp - Example of a Graph built from STL's map.
*
* $Id: graph.cpp 580483 2007-09-28 20:55:52Z sebor $
*
***************************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* Copyright 1994-2006, 2007 Rogue Wave Software, Inc.
*
**************************************************************************/
#include <map>
#include <vector>
#include <queue>
#include <iostream>
#include <string>
#include <examples.h>
typedef std::map<std::string, int> Distances;
typedef std::map<std::string, Distances> Cities;
typedef std::pair<unsigned, std::string> DistancePair;
bool operator< (const DistancePair& lhs, const DistancePair& rhs) {
return lhs.first < rhs.first;
}
bool operator> (const DistancePair& lhs, const DistancePair& rhs) {
return lhs.first > rhs.first;
}
static void
shortestDistance (Cities &city_map,
const std::string &start_city,
Distances &dist)
{
// Process a priority queue of distances to nodes.
std::priority_queue<DistancePair,
std::vector<DistancePair,
std::allocator<DistancePair> >,
std::greater<DistancePair> > que;
que.push (DistancePair (0, start_city));
while (! que.empty ()) {
// Pull nearest city from queue.
int distance = que.top ().first;
std::string city = que.top ().second;
que.pop ();
// If we haven't seen it already, process it.
if (0 == dist.count (city))
{
// Then add it to shortest distance map.
dist[city] = distance;
// And put values into queue.
const Distances& cities = city_map[city];
Distances::const_iterator start = cities.begin ();
Distances::const_iterator stop = cities.end ();
for (; start != stop; ++start)
que.push (DistancePair (distance + (*start).second,
(*start).first));
}
}
}
int main () {
std::cout << "Graph example program "
<< " - find shortest path in a directed graph."
<< std::endl;
static const char pendleton[] = "Pendleton";
static const char pensacola[] = "Pensacola";
static const char peoria[] = "Peoria";
static const char phoenix[] = "Phoenix";
static const char pierre[] = "Pierre";
static const char pittsburgh[] = "Pittsburgh";
static const char princeton[] = "Princeton";
static const char pueblo[] = "Pueblo";
Cities cityMap;
cityMap[pendleton][phoenix] = 4;
cityMap[pendleton][pueblo] = 8;
cityMap[pensacola][phoenix] = 5;
cityMap[peoria][pittsburgh] = 5;
cityMap[peoria][pueblo] = 3;
cityMap[phoenix][peoria] = 4;
cityMap[phoenix][pittsburgh] = 10;
cityMap[phoenix][pueblo] = 3;
cityMap[pierre][pendleton] = 2;
cityMap[pittsburgh][pensacola] = 4;
cityMap[princeton][pittsburgh] = 2;
cityMap[pueblo][pierre] = 3;
Distances dist;
shortestDistance (cityMap, pierre, dist);
Distances::iterator where;
std::cout << "Find the shortest path from : "
<< pierre << '\n';
for (where = dist.begin (); where != dist.end (); ++where)
std::cout << " Distance to: " << (*where).first << ":"
<< (*where).second << '\n';
std::cout << "End of graph example program" << '\n';
return 0;
}

View File

@@ -0,0 +1,230 @@
/**************************************************************************
*
* icecream.cpp - Priority queue example program.
*
* $Id: icecream.cpp 595289 2007-11-15 12:34:31Z faridz $
*
***************************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* Copyright 1994-2006 Rogue Wave Software.
*
**************************************************************************/
#include <algorithm> // for random_shuffle()
#include <iostream> // for cout
#include <queue> // for queue
#include <vector> // for vector
#include <examples.h>
// Execution event in a descrete event driven simulation.
class event {
public:
// Construct sets time of event.
event (unsigned int t) : time (t)
{ }
// Execute event by invoking this method.
virtual void processEvent () = 0;
const unsigned int time;
};
struct eventComparator {
bool operator() (const event * left, const event * right) const {
return left->time > right->time;
}
};
// Framework for discrete event-driven simulations.
class simulation {
public:
simulation () : time (0), eventQueue ()
{}
void run ();
void scheduleEvent (event * newEvent) {
eventQueue.push (newEvent);
}
unsigned int time;
protected:
std::priority_queue<event*,
std::vector<event *, std::allocator<event*> >,
eventComparator> eventQueue;
};
void simulation::run () {
while (! eventQueue.empty ()) {
event * nextEvent = eventQueue.top ();
eventQueue.pop ();
time = nextEvent->time;
nextEvent->processEvent ();
delete nextEvent;
}
}
// Ice cream store simulation.
class storeSimulation : public simulation {
public:
storeSimulation () : simulation (), freeChairs (35), profit (0.0)
{ }
bool canSeat (unsigned int numberOfPeople);
void order (unsigned int numberOfScoops);
void leave (unsigned int numberOfPeople);
// Data fields.
unsigned int freeChairs;
double profit;
} theSimulation;
class arriveEvent : public event {
public:
arriveEvent (unsigned int t, unsigned int groupSize)
: event (t), size (groupSize)
{ }
virtual void processEvent ();
private:
unsigned int size;
};
class orderEvent : public event {
public:
orderEvent (unsigned int t, unsigned int groupSize)
: event (t), size (groupSize)
{ }
virtual void processEvent ();
private:
unsigned int size;
};
class leaveEvent : public event
{
public:
leaveEvent (unsigned int t, unsigned int groupSize)
: event (t), size (groupSize)
{ }
virtual void processEvent ();
private:
unsigned int size;
};
// returns a random integer between 0 and n with n <= 32767 <= INT_MAX
int irand (int n)
{
static int seq[] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf
};
std::random_shuffle (seq, seq + sizeof seq / sizeof *seq);
const int rnd = (seq [0] << 11) | (seq [1] << 8) | (seq [2] << 4) + seq [3];
return rnd % n;
}
void arriveEvent::processEvent () {
if (theSimulation.canSeat (size))
theSimulation.scheduleEvent
(new orderEvent (time + 1 + irand (4), size));
}
void orderEvent::processEvent () {
// Each person orders some number of scoops.
for (unsigned int i = 0; i < size; i++)
theSimulation.order (1 + irand (4));
// Then we schedule the leave event.
theSimulation.scheduleEvent
(new leaveEvent (time + 1 + irand (10), size));
}
void leaveEvent::processEvent () {
theSimulation.leave (size);
}
// If sufficient room then seat customers.
bool storeSimulation::canSeat (unsigned int numberOfPeople) {
std::cout << "Time: " << time;
std::cout << " group of " << numberOfPeople << " customers arrives";
if (numberOfPeople < freeChairs) {
std::cout << " is seated\n";
freeChairs -= numberOfPeople;
return true;
}
else {
std::cout << " no room, they leave\n";
return false;
}
}
// Service icecream, compute profits.
void storeSimulation::order (unsigned int numberOfScoops) {
std::cout << "Time: " << time << " serviced order for "
<< numberOfScoops << '\n';
profit += 0.35 * numberOfScoops;
}
// People leave, free up chairs.
void storeSimulation::leave (unsigned int numberOfPeople) {
std::cout << "Time: " << time << " group of size "
<< numberOfPeople << " leaves\n";
freeChairs += numberOfPeople;
}
int main () {
std::cout << "Ice Cream Store simulation from Chapter 9\n";
// Load queue with some number of initial events.
for (unsigned t = 0; t < 20; t += irand (6)) {
std::cout << "pumping queue with event " << t << '\n';
theSimulation.scheduleEvent (new arriveEvent (t, 1 + irand (4)));
}
// Run the simulation.
theSimulation.run ();
std::cout << "Total profits " << theSimulation.profit
<< "\nEnd of ice cream store simulation\n";
return 0;
}

View File

@@ -0,0 +1 @@
5 4 3 2 1 + * - / p q

View File

@@ -0,0 +1,4 @@
Twas brillig and the slithy toves
Did gyre and gimble in the wabe
All mimsy were the borogroves
And the mome raths outgrabe

View File

@@ -0,0 +1 @@
a man a plan a canal panama

View File

@@ -0,0 +1,2 @@
y
q

View File

@@ -0,0 +1,18 @@
STL generic algorithms -- initialization algorithms
Illustrate fill function
xxxxxxxxxx
empty empty empty empty empty empty empty empty empty empty
full full full full full full full full full full
00000078910
Illustrate copy function
surprise
big surprise
Illustrate generate algorithm
L_0 L_1 L_2 L_3
7 8 9 10 11 7 8 9 10 11
Illustrate swap_ranges algorithm
14 27 12 64
4 2 3 1
4 2 3 1
14 27 12 64
End of initialization tests

View File

@@ -0,0 +1,23 @@
STL generic algorithms -- Searching Algorithms
Test of algorithm find
first vintage leap year is 1972
1995 is position 4 in sequence
Test of algorithm find adjacent
In the text The bookkeeper carefully opened the door
double o in position 5
double k in position 7
double e in position 9
double l in position 21
double o in position 37
Test of algorithm search
substring begins in position 4
Test of max and min algorithms
largest value was 93
smallest value was 11
The smallest word is best and the largest word is worst
string goody is equal to goody
string good is less than goody
string goody is greater than good
string good is greater than fred
string fred is less than good
End of search algorithms test program

View File

@@ -0,0 +1,44 @@
STL generic algorithms -- in-place algorithms
Illustrate std::reverse() algorithm
<Rats live on no evil star>
>rats live on no evil staR<
2 3 4 5 6 7 8 9 10 11
11 10 9 8 7 6 5 4 3 2
Illustrate std::replace() algorithm
0 1 2 3 4 5 4 3 2 1 0
0 1 2 7 4 5 4 7 2 1 0
9 1 9 7 9 5 9 7 9 1 9
7 1 4 3 7 5
8 1 8 3 8 8
Illustrate std::rotate() algorithm
7 8 9 10 1 2 3 4 5 6
3 4 5 6 7 8 9 10 1 2
Illustrate std::partition() algorithm
10 2 8 4 6 5 7 3 9 1
middle location 5
1 2 3 4 5 6 7 8 9 10
Illustrate std::next_permutation() algorithm
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
Alpha Beta Gamma
Alpha Gamma Beta
Beta Alpha Gamma
Beta Gamma Alpha
Gamma Alpha Beta
Gamma Beta Alpha
Illustrate std::prev_permutation() algorithm
bela beal bale bael aleb albe aelb aebl able abel
Illustrate std::inplace_merge() algorithm
0 2 4 6 8 1 3 5 7 9
0 2 4 6 8 1 3 5 7 9
0 1 2 3 4 5 6 7 8 9
Illustrate std::generate() algorithm
1 2 3 4 5 6 7 8 9 10
Illustrate std::random_shuffle() algorithm
10 9 1 7 8 4 5 6 2 3
4 2 6 5 9 3 10 7 1 8
End of in-place algorithm sample program

View File

@@ -0,0 +1,12 @@
STL generic algorithms -- Removal Algorithms
Remove Algorithm examples
Original list: 1 2 4 3 1 4 2
After removing 2's: 1 4 3 1 4
List after removal, before erase: 1 4 3 1 4 4 2
List after erase: 1 4 3 1 4
List after removing even values: 1 3 1
Origianal List: 1 3 3 2 2 4
Set after unique_copy: 1 2 3 4
List after calling unique: 1 3 2 4 2 4
List after erase: 1 3 2 4
End of removal algorithms sample program

View File

@@ -0,0 +1,15 @@
STL generic algorithms -- algorithms that produce scalar results
There are 3 letter e's
and 8 vowels in the text:Now is the time to begin
The sum of the first five numbers is 15
The product of the first five numbers is 120
1 2 1 3 2 1 4 3 2 1 5 4 3 2 1
Inner product is 33
any equal? 1
a = b is:0
a = c is:1
a pair-wise-greater_equal b is1
compare everybody to everything 1
compare a to b: 0
compare a to c: 1
End of scalar algorithms test

View File

@@ -0,0 +1,12 @@
STL generic algorithms -- that transform sequences
Original list: 1 2 3 4 5 6
After squaring: 1 4 9 16 25 36
After squaring again: 1 16 81 256 625 1296
After division: 1 8 27 64 125 216
Partial sums examples
Partial sums : 1 3 6 10 15
Partial products: 1 2 6 24 120
Adjacent Differences examples
Adjacent Differences : 1 1 1 1 1
Adjacent sums: 1 3 5 7 9
End generic transform algorithms example

View File

@@ -0,0 +1,32 @@
Sorting generic algorithms examples
Sort algorithms
4 4 10 13 37 50 51 56 63 67 76 79 85 87 89
81 79 75 64 61 61 57 56 39 39 35 30 18 13 7
89 87 85 79 76 67 63 56 51 50 37 13 10 4 4
Partial sort examples
42 97 8 74 94 98 92 36 7 97 87 85 1 24 67
1 7 8 24 36 42 67 98 97 97 94 92 87 85 74
59 9 1 49 84 20 34 98 87 30 71 69 30 15 23
98 87 84 71 69 59 49
Nth largest example
fifth largest is 56 in
19 27 27 43 56 70 94 75 95 82
Binary search example
1 6 8 10 31 45 45 58 69 70 75 85 86 94 95
does not contain an 11
1 6 8 10 11 14 31 45 45 58 69 70 75 85 86 94 95
Merge algorithm examples
7 8 17 36 36 43 50 52 54 60 64 68 72 75 76 81 83 90 94 98
Set operations:
1 2 3 4 5 6 7
1 2 3 3 4 4 5 5 6 7
3 4 5
1 2
1 2 6 7
set is not subset
93 86 87 85 78 80 84 83 74 1 19 32 43 9 8
Largest value 93
87 86 84 85 78 80 9 83 74 1 19 32 43 8
97 86 87 85 78 80 84 83 74 1 19 32 43 8 9
1 8 9 19 32 43 74 78 80 83 84 85 86 87 97
End sorting examples

View File

@@ -0,0 +1 @@
Assertion - executable does not exist.

View File

@@ -0,0 +1,4 @@
Calculator example program, from Chapter 8
Enter a legal RPN expression, end with p q (print and quit)
-1
End calculator program

View File

@@ -0,0 +1 @@
Roots are (-0.949179,-1.25199) and (-0.820052,1.40583)

View File

@@ -0,0 +1,22 @@
Concordance sample program, from Chapter 7
Enter text, then end-of-file:
all: 3
and: 1 2 4
borogroves: 3
brillig: 1
did: 2
gimble: 2
gyre: 2
in: 2
mimsy: 3
mome: 4
outgrabe: 4
raths: 4
slithy: 1
the: 1 2 3 4
toves: 1
twas: 1
wabe: 2
were: 3
End of concordance sample program

View File

@@ -0,0 +1,6 @@
static_cast<const int&>(v1 = 1) = 1
static_cast<const double&>(v1 = 3.14) = 3.14
static_cast<const double&>(v2 = v1) = 3.14
static_cast<const char* const&>(v2 = "abc") = abc
static_cast<const char* const&>(v1 = v2) = abc
static_cast<const char&>(v3) = exception

View File

@@ -0,0 +1,10 @@
Graph example program - find shortest path in a directed graph.
Find the shortest path from : Pierre
Distance to: Pendleton:2
Distance to: Pensacola:19
Distance to: Peoria:10
Distance to: Phoenix:6
Distance to: Pierre:0
Distance to: Pittsburgh:15
Distance to: Pueblo:9
End of graph example program

View File

@@ -0,0 +1,56 @@
Ice Cream Store simulation from Chapter 9
pumping queue with event 0
pumping queue with event 0
pumping queue with event 2
pumping queue with event 7
pumping queue with event 8
pumping queue with event 12
pumping queue with event 12
pumping queue with event 12
pumping queue with event 14
pumping queue with event 17
Time: 0 group of 2 customers arrives is seated
Time: 0 group of 4 customers arrives is seated
Time: 2 group of 3 customers arrives is seated
Time: 3 serviced order for 4
Time: 3 serviced order for 1
Time: 3 serviced order for 1
Time: 3 serviced order for 3
Time: 4 serviced order for 4
Time: 4 serviced order for 1
Time: 4 group of size 4 leaves
Time: 5 serviced order for 2
Time: 5 serviced order for 1
Time: 5 serviced order for 3
Time: 7 group of 1 customers arrives is seated
Time: 7 group of size 2 leaves
Time: 7 group of size 3 leaves
Time: 8 group of 3 customers arrives is seated
Time: 10 serviced order for 3
Time: 12 group of 2 customers arrives is seated
Time: 12 group of 3 customers arrives is seated
Time: 12 serviced order for 2
Time: 12 serviced order for 2
Time: 12 serviced order for 4
Time: 12 group of 1 customers arrives is seated
Time: 14 serviced order for 3
Time: 14 serviced order for 4
Time: 14 group of 2 customers arrives is seated
Time: 15 serviced order for 4
Time: 16 serviced order for 1
Time: 16 serviced order for 3
Time: 16 serviced order for 2
Time: 17 serviced order for 2
Time: 17 serviced order for 2
Time: 17 group of 2 customers arrives is seated
Time: 18 group of size 1 leaves
Time: 19 group of size 1 leaves
Time: 21 group of size 2 leaves
Time: 21 group of size 3 leaves
Time: 21 group of size 3 leaves
Time: 21 serviced order for 3
Time: 21 serviced order for 4
Time: 24 group of size 2 leaves
Time: 27 group of size 2 leaves
Total profits 20.65
End of ice cream store simulation

View File

@@ -0,0 +1,7 @@
Radix sort program
730 301 852 593 624 415 426 146 987 78 269
301 415 624 426 730 146 852 269 78 987 593
78 146 269 301 415 426 593 624 730 852 987
78 146 269 301 415 426 593 624 730 852 987
78 146 269 301 415 426 593 624 730 852 987
End radix sort program

View File

@@ -0,0 +1,3 @@
Prime Sieve program, a test of vectors
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
End of Prime Sieve program

View File

@@ -0,0 +1,8 @@
Enter text:
Misspelled words:
a
canal
man
panama
plan
End of spell check program

View File

@@ -0,0 +1,16 @@
Telephone Directory sample program
Allen:6348723
Brenda:5436546
Fred:7435423
Samantha:6342343
Listing for prefix 634
Allen:6348723
Samantha:6342343
end of prefix listing
Display by prefix
5436546:Brenda
6342343:Samantha
6348723:Allen
7435423:Fred
end display by prefix
End of telephone directory sample program

View File

@@ -0,0 +1 @@
average wait: 0.781818

View File

@@ -0,0 +1,13 @@
Widget Works test program
Received shipment of widget type 1
Received shipment of widget type 2
Received shipment of widget type 3
Received order for widget type 2
Ship Widget 2
Received order for widget type 2
Back order widget of type 2
Received order for widget type 3
Ship Widget 3
Received shipment of widget type 2
Ship Widget 2 to fill back order
End of widget words test program

View File

@@ -0,0 +1,106 @@
/**************************************************************************
*
* radix.cpp - Radix sort employing various STL classes.
*
* $Id: radix.cpp 550991 2007-06-26 23:58:07Z sebor $
*
***************************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* Copyright 1994-2006 Rogue Wave Software.
*
**************************************************************************/
#include <deque>
#include <list>
#include <vector>
#include <algorithm>
#include <numeric>
#include <iostream>
#include <iterator>
#include <examples.h>
typedef std::deque<int, std::allocator<int> > IntDeque;
typedef std::vector<IntDeque, std::allocator<IntDeque> > DeqVector;
typedef std::list<int, std::allocator<int> > IntList;
typedef std::ostream_iterator<int, char, std::char_traits<char> > OstreamIter;
class copyIntoBuckets {
public:
copyIntoBuckets (int d, DeqVector &b, bool &f)
: divisor (d), buckets (b), flag (f)
{}
void operator () (unsigned int v) {
const int inx = (v / divisor) % 10;
// flag set to true if any bucket other than the 0-th one is used
if (inx)
flag = true;
buckets [inx].push_back (v);
}
int divisor;
DeqVector &buckets;
bool &flag;
};
IntList::iterator
copyList (IntList::iterator c, IntDeque &lst) {
return std::copy (lst.begin (), lst.end (), c);
}
void radixSort (IntList & values) {
bool flag = true;
int divisor = 1;
while (flag)
{
DeqVector buckets (10);
flag = false;
std::for_each (values.begin (), values.end (),
copyIntoBuckets (divisor, buckets, flag));
std::accumulate (buckets.begin (), buckets.end (), values.begin (), copyList);
divisor *= 10;
std::copy (values.begin (), values.end (), OstreamIter (std::cout, " "));
std::cout << std::endl;
}
}
int main () {
std::cout << "Radix sort program" << std::endl;
const IntList::value_type data[] = { 624, 852, 426, 987, 269,
146, 415, 301, 730, 78, 593 };
IntList values (data, data + sizeof data / sizeof *data);
radixSort (values);
std::copy (values.begin (), values.end (), OstreamIter (std::cout, " "));
std::cout << std::endl << "End radix sort program" << std::endl;
return 0;
}

View File

@@ -0,0 +1,57 @@
/**************************************************************************
*
* sieve.cpp - Prime numbers sieve program.
*
* $Id: sieve.cpp 550991 2007-06-26 23:58:07Z sebor $
*
***************************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* Copyright 1994-2006 Rogue Wave Software.
*
**************************************************************************/
#include <vector>
#include <iostream>
#include <examples.h>
int main ()
{
std::cout << "Prime Sieve program, a test of vectors" << std::endl;
// Create a sieve of bits, initially set to 1.
const int sievesize = 100;
std::vector<int, std::allocator<int> > sieve ((std::size_t)sievesize, 1);
// At positions that are multiples of i, set value to zero.
for (int i = 2; i * i < sievesize; i++)
if (sieve[i])
for (int j = i + i; j < sievesize; j += i)
sieve[j] = 0;
// Now output all the values that are still set.
for (int j = 2; j < sievesize; j++)
if (sieve[j])
std::cout << j << " ";
std::cout << std::endl << "End of Prime Sieve program" << std::endl;
return 0;
}

View File

@@ -0,0 +1,78 @@
/**************************************************************************
*
* spell.cpp - A spell checking program.
*
* $Id: spell.cpp 648752 2008-04-16 17:01:56Z faridz $
*
***************************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* Copyright 1994-2006 Rogue Wave Software.
*
**************************************************************************/
#include <fstream>
#include <iostream>
#include <iterator>
#include <set>
#include <string>
#include <examples.h>
typedef
std::set <std::string,
std::less<std::string>, std::allocator<std::string> > stringset;
typedef
std::ostream_iterator<std::string,
char, std::char_traits<char> > ostrm_iter;
typedef
std::istream_iterator<std::string,
char, std::char_traits<char>,
std::ptrdiff_t> istrm_iter;
void spellCheck (std::istream & dictionary, std::istream & text) {
stringset words, misspellings;
std::string word;
istrm_iter eof, dstream (dictionary);
// First read the dictionary.
std::copy (dstream, eof, std::inserter (words, words.begin ()));
// Next read the text.
while (text >> word)
if (! words.count (word))
misspellings.insert (word);
// Finally, output all misspellings.
std::cout << std::endl << "Misspelled words:" << std::endl;
std::copy (misspellings.begin (), misspellings.end (),
ostrm_iter (std::cout, "\n"));
}
int main ()
{
std::cout << "Enter text:";
std::ifstream words ("words");
spellCheck (words, std::cin);
std::cout << "End of spell check program" << std::endl;
return 0;
}

View File

@@ -0,0 +1,91 @@
/**************************************************************************
*
* stdexcept.cpp - Illustrate the use of C++ Standard Library exceptions.
*
* $Id: stdexcept.cpp 550991 2007-06-26 23:58:07Z sebor $
*
***************************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* Copyright 1994-2005 Rogue Wave Software.
*
**************************************************************************/
#include <string> // for string
#include <stdexcept> // for exception, runtime_error, out_of_range
#include <iostream> // for cout
#include <examples.h>
#ifndef _RWSTD_NO_EXCEPTIONS
int main () {
// First we'll incite and catch an exception from the C++ Standard
// library class std::string by attempting to replace a substring
// starting at a position beyond the end of the string object.
try {
std::string ().replace (100, 1, 1, 'c');
}
catch (std::out_of_range &e) {
// Print out the exception string, which in this implementation
// includes the location and the name of the function that threw
// the exception along with the reason for the exception.
std::cout << "Caught an out_of_range exception: "
<< e.what () << '\n';
}
catch (std::exception &e) {
std::cout << "Caught an exception of an unexpected type: "
<< e.what () << '\n';
}
catch (...) {
std::cout << "Caught an unknown exception\n";
}
// Throw another exception.
try {
throw std::runtime_error ("a runtime error");
}
catch (std::runtime_error &e) {
std::cout << "Caught a runtime_error exception: "
<< e.what () << '\n';
}
catch (std::exception &e) {
std::cout << "Caught an exception of an unexpected type: "
<< e.what () << '\n';
}
catch (...) {
std::cout << "Caught an unknown exception\n";
}
return 0;
}
#else // if defined (_RWSTD_NO_EXCEPTIONS)
int main () {
std::cout << "Exception support disabled.\n";
return 0;
}
#endif // _RWSTD_NO_EXCEPTIONS

View File

@@ -0,0 +1,208 @@
/**************************************************************************
*
* stocks.cpp - An example program using STL's money_punct, num_put
* and time_put locale facets.
*
* $Id: stocks.cpp 636370 2008-03-12 15:32:56Z faridz $
*
***************************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* Copyright 1994-2006 Rogue Wave Software.
*
**************************************************************************/
#include <clocale>
#include <iostream>
#include <locale>
#include <stocks.h>
#include <examples.h>
// definition of the required facet id
std::locale::id StockXchange::id;
StockXchange::~StockXchange ()
{
database::const_iterator begin = companyDatabase.begin ();
database::const_iterator end = companyDatabase.end ();
while (begin < end)
delete *begin++;
}
void StockXchange::localTime (std::ostream& os) const
{
const char pat[] = "%c";
typedef std::time_put<char, iter_type> TimePut;
const TimePut& tp = std::use_facet<TimePut>(os.getloc ());
iter_type begin (os);
os << "\t [";
tp.put (begin, os, ' ', &tmb, &pat [0], pat + sizeof pat - 1);
os << "]\n";
}
void StockXchange::add (const std::string& name, double initPrice)
{
companyDatabase.push_front (new Company (name, initPrice));
}
bool StockXchange::put (std::ostream& os) const
{
std::locale loc = os.getloc ();
localTime (os); //display the local time
typedef std::moneypunct<char, false> MoneyPunct;
const MoneyPunct &mpunct = std::use_facet<MoneyPunct>(loc);
typedef std::num_put<char, iter_type> NumPut;
const NumPut &np = std::use_facet<NumPut>(loc);
os << "\nCompany" << "\t\t\t" << "Initial Price" << "\t"
<< "Current Price" << "\t" << "Volume\n"
<< "-------" << "\t\t\t" << "------------" << "\t"
<< "----------" << "\t" << "______\n\n";
iter_type itbegin (os);
database::const_iterator begin = companyDatabase.begin ();
database::const_iterator end = companyDatabase.end ();
while (begin < end) {
Company *info = *begin++;
info->updateStock ();
os << info->companyName << "\t\t";
os << mpunct.curr_symbol ();
np.put (itbegin, os, ' ', info->offerPrice);
os << "\t\t";
os << mpunct.curr_symbol ();
np.put (itbegin, os, ' ', info->stockPrice);
os << "\t\t";
long volume = stock_change[info->changeIndex ()]*1000L;
if (volume < 0)
volume = -volume;
np.put (itbegin, os, ' ', volume);
os << '\n';
}
return true;
}
std::ostream & operator<< (std::ostream& os, const StockXchange&)
{
const std::locale loc = os.getloc ();
const StockXchange &se_facet = std::use_facet<StockXchange>(loc);
se_facet.put (os);
return os;
}
int main ()
{
typedef std::pair<StockXchange*, std::locale> sl_pair;
typedef std::deque<sl_pair, std::allocator<sl_pair> > Xchange;
Xchange sXchange;
std::ostream os (std::cout.rdbuf ());
const std::locale loc (os.getloc ());
const char *p = std::setlocale (LC_ALL, US_LOCALE);
if (!p)
std::cerr << "\nNot a valid locale: " << US_LOCALE << '\n';
else {
NewYorkStockXchange *nse = new NewYorkStockXchange;
nse->add ("Hyper Software", 20.50);
nse->add ("Florida Fish", 15.10);
nse->add ("Inka Inc", 9.50);
nse->add ("Emory Chemicals", 11.00);
os.imbue (std::locale (std::locale (US_LOCALE), nse));
sXchange.push_front (sl_pair (nse, os.getloc ()));
os << *nse;
}
p = std::setlocale (LC_ALL, GERMAN_LOCALE);
if (!p)
std::cerr<< "\nNot a valid locale: " << GERMAN_LOCALE << '\n';
else {
FrankfurtStockXchange *fse = new FrankfurtStockXchange;
fse->add ("B\166rsen-Software", 9.75);
fse->add ("M\174nchner R\174ck", 19.75);
os.imbue (std::locale (std::locale (GERMAN_LOCALE), fse));
sXchange.push_front (sl_pair (fse, os.getloc ()));
os << *fse;
}
p = std::setlocale (LC_ALL, FRENCH_LOCALE);
if (!p)
std::cerr << "\nNot a valid locale: " << FRENCH_LOCALE << '\n';
else {
ParisStockXchange *pse = new ParisStockXchange;
pse->add ("Wines Inc.", 11.50);
pse->add ("Eiffel Co.", 11.50);
os.imbue (std::locale (std::locale (FRENCH_LOCALE), pse));
sXchange.push_front (sl_pair (pse, os.getloc ()));
os << *pse;
}
p = std::setlocale (LC_ALL, JAPANESE_LOCALE);
if (!p)
std::cerr << "\nNot a valid locale: " << JAPANESE_LOCALE << '\n';
else {
TokyoStockXchange *tse = new TokyoStockXchange;
tse->add ("Akiro Electronics", 12.30);
os.imbue (std::locale (std::locale (JAPANESE_LOCALE), tse));
sXchange.push_front (sl_pair (tse, os.getloc ()));
os << *tse;
}
for (char q = '\0'; ; ) {
std::cout << "\nWant to see another quote [enter 'q' to quit] ?";
std::cin >> q;
if (q != 'q') {
Xchange::const_iterator it_begin = sXchange.begin ();
Xchange::const_iterator it_end = sXchange.end ();
while (it_begin < it_end) {
os.imbue ((*it_begin).second);
os << (*(*it_begin).first);
it_begin++;
}
}
else
break;
}
os << '\n';
os.imbue (loc);
return 0;
}

View File

@@ -0,0 +1,145 @@
/**************************************************************************
*
* tele.cpp - Telephone directory sample program.
*
* $Id: tele.cpp 550991 2007-06-26 23:58:07Z sebor $
*
***************************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* Copyright 1994-2006 Rogue Wave Software.
*
**************************************************************************/
#include <map>
#include <algorithm>
#include <vector>
#include <string>
#include <iostream>
#include <examples.h>
typedef std::map<std::string, long, std::less<std::string>,
std::allocator<std::pair<const std::string, long> > > friendMap;
typedef std::map<long, std::string, std::less<long>,
std::allocator<std::pair<const long, std::string> > > sortedMap;
typedef friendMap::value_type entry_type;
typedef sortedMap::value_type sorted_entry_type;
void printEntry (const entry_type & entry) {
std::cout << entry.first << ":" << entry.second << std::endl;
}
void printSortedEntry (const sorted_entry_type & entry) {
std::cout << entry.first << ":" << entry.second << std::endl;
}
long prefix (const entry_type& entry) {
return entry.second / 10000;
}
bool prefixCompare (const entry_type & a, const entry_type & b) {
return prefix (a) < prefix (b);
}
class checkPrefix {
public:
checkPrefix (long p) : testPrefix (p)
{ }
long testPrefix;
bool operator () (const entry_type& entry) {
return prefix (entry)==testPrefix;
}
};
class telephoneDirectory {
public:
void addEntry (std::string name, long number) {
database[name] = number;
}
void remove (std::string name) {
database.erase (name);
}
void update (std::string name, long number) {
remove (name);addEntry (name, number);
}
void displayDatabase () {
std::for_each (database.begin (), database.end (), printEntry);
}
void displayPrefix (int);
void displayByPrefix ();
private:
friendMap database;
};
void telephoneDirectory::displayPrefix (int pfx) {
std::cout << "Listing for prefix " << pfx << std::endl;
friendMap::iterator
where = std::find_if (database.begin (), database.end (),
checkPrefix (pfx));
while (where != database.end ()) {
printEntry (*where);
where = std::find_if (++where, database.end (), checkPrefix (pfx));
}
std::cout << "end of prefix listing" << std::endl;
}
void telephoneDirectory::displayByPrefix () {
std::cout << "Display by prefix" << std::endl;
sortedMap sortedData;
for (friendMap::iterator i = database.begin (); i != database.end (); i++)
sortedData.insert (sortedMap::value_type ((*i).second, (*i).first));
std::for_each (sortedData.begin (), sortedData.end (), printSortedEntry);
std::cout << "end display by prefix" << std::endl;
}
int main () {
std::cout << "Telephone Directory sample program" << std::endl;
telephoneDirectory friends;
friends.addEntry ("Samantha", 6342343);
friends.addEntry ("Brenda", 5436546);
friends.addEntry ("Fred", 7435423);
friends.addEntry ("Allen", 6348723);
friends.displayDatabase ();
friends.displayPrefix (634);
friends.displayByPrefix ();
std::cout << "End of telephone directory sample program" << std::endl;
return 0;
}

View File

@@ -0,0 +1,78 @@
/**************************************************************************
*
* teller.cpp - Bank teller sample program.
*
* $Id: teller.cpp 550991 2007-06-26 23:58:07Z sebor $
*
***************************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* Copyright 1994-2006 Rogue Wave Software.
*
**************************************************************************/
#include <queue>
#include <iostream>
#include <vector>
#include <teller.h>
// A very unsatisfactory, but very portable implementation
// of a linear congruential pseudorandom number generator.
// (Apologies to D. Lehmer, D. Knuth, R. Sedgewick, et al.)
static unsigned long int lcg_seed = 0;
inline unsigned long int lcg_rand (int n)
{
lcg_seed = ((lcg_seed * 11321) + 1) % 32575;
return (int) (((double) lcg_seed / 32575.0) * n);
}
int main ()
{
const int numberOfTellers = 5;
const int numberOfMinutes = 60;
double totalWait = 0;
int numberOfCustomers = 0;
std::vector<Teller> teller (numberOfTellers);
std::queue<Customer> line;
for (int t = 0; t < numberOfMinutes; t++) {
if (lcg_rand (10) < 9)
line.push (Customer (t));
for (int i = 0; i < numberOfTellers; i++) {
if (teller[i].isFree () && !line.empty ()) {
Customer& frontCustomer = line.front ();
numberOfCustomers++;
totalWait += t - frontCustomer.arrivalTime;
teller[i].addCustomer (frontCustomer);
line.pop ();
}
}
}
std::cout << "average wait: "
<< (totalWait / numberOfCustomers) << std::endl;
return 0;
}

View File

@@ -0,0 +1,118 @@
/**************************************************************************
*
* widwork.cpp - Widget works inventory example.
*
* $Id: widwork.cpp 550991 2007-06-26 23:58:07Z sebor $
*
***************************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* Copyright 1994-2006 Rogue Wave Software.
*
**************************************************************************/
#include <algorithm>
#include <examples.h>
#include <widwork.h>
std::ostream& operator<< ( std::ostream& out, const Widget& w )
{
return out << "Widget " << w.id;
}
bool operator== (const Widget& lhs, const Widget& rhs) {
return lhs.id == rhs.id;
}
bool operator< (const Widget& lhs, const Widget& rhs) {
return lhs.id < rhs.id;
}
bool WidgetTester::operator () (const Widget & wid, int testid) const
{
return wid.id == testid;
}
void inventory::order (int wid) {
std::cout << "Received order for widget type " << wid << std::endl;
widgetList::iterator
wehave = std::find_if (on_hand.begin (), on_hand.end (),
std::bind2nd (WidgetTester (), wid));
if (wehave != on_hand.end ()) {
std::cout << "Ship " << *wehave << std::endl;
on_hand.erase (wehave);
}
else {
std::cout << "Back order widget of type " << wid << std::endl;
on_order.push_front (wid);
}
}
void inventory::receive (int wid) {
std::cout << "Received shipment of widget type " << wid << std::endl;
idList::iterator weneed = std::find (on_order.begin (),
on_order.end (), wid);
if (weneed != on_order.end ()) {
std::cout << "Ship " << Widget (wid) << " to fill back order"
<< std::endl;
on_order.erase (weneed);
}
else
on_hand.push_front (Widget (wid));
}
int main ()
{
std::cout << "Widget Works test program" << std::endl;
inventory stock;
stock.receive (1);
stock.receive (2);
stock.receive (3);
stock.order (2);
stock.order (2);
stock.order (3);
stock.receive (2);
std::cout << "End of widget words test program" << std::endl;
return 0;
}