第二十章
20.5(冒泡排序)
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
int main()
{
const int SIZE = 10;
int data[SIZE] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
vector < int > a;
for (int i = 0; i < SIZE; i++)
a.push_back(data[i]);
int hold;
cout << "Data items in original order\n";
for (int i = 0; i < SIZE; i++)
cout << setw(4) << a[i];
for (int pass = 0; pass < SIZE - 1; pass++)
{
for (int j = 0; j < SIZE - 1; j++)
{
if (a[j] > a[j + 1])
{
hold = a[j];
a[j] = a[j + 1];
a[j + 1] = hold;
}
}
}
cout << "\nData items in ascending order\n";
for (int k = 0; k < SIZE; k++)
cout << setw(4) << a[k];
cout << endl;
}
20.6(增强的冒泡排序)
a
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
int main()
{
const int SIZE = 10;
int data[SIZE] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
vector < int > a;
for (int i = 0; i < SIZE; i++)
a.push_back(data[i]);
int hold;
int numberOfComp = 0;
int comp;
cout << "Data items in original order\n";
for (int i = 0; i < SIZE; i++)
cout << setw(4) << a[i];
cout << "\n\n";
for (int pass = 1; pass < SIZE; pass++)
{
cout << "After pass " << pass - 1 << ": ";
for (comp = 0; comp < SIZE - pass; comp++)
{
++numberOfComp;
if (a[comp] > a[comp + 1])
{
hold = a[comp];
a[comp] = a[comp + 1];
a[comp + 1] = hold;
}
cout << setw(3) << a[comp];
}
cout << setw(3) << a[comp] << '\n';
}
cout << "\nData items in ascending order\n";
for (int j = 0; j < SIZE; j++)
cout << setw(4) << a[j];
cout << "\nNumber of comparisons = " << numberOfComp << endl;
}
b
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
int main()
{
const int SIZE = 10;
int data[SIZE] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
vector < int > a;
for (int i = 0; i < SIZE; i++)
a.push_back(data[i]);
int hold;
int numberOfComp = 0;
int comp;
bool swapCheck = true;
cout << "Data items in original order\n";
for (int i = 0; i < SIZE; i++)
cout << setw(4) << a[i];
cout << "\n\n";
for (int pass = 1; pass < SIZE && swapCheck; pass++)
{
cout << "After pass " << pass - 1 << ": ";
swapCheck = false;
for (comp = 0; comp < SIZE - pass; comp++)
{
++numberOfComp;
if (a[comp] > a[comp + 1])
{
hold = a[comp];
a[comp] = a[comp + 1];
a[comp + 1] = hold;
swapCheck = true;
}
cout << setw(3) << a[comp];
}
cout << setw(3) << a[comp] << '\n';
}
cout << "\nData items in ascending order\n";
for (int j = 0; j < SIZE; j++)
cout << setw(4) << a[j];
cout << "\nNumber of comparisons = " << numberOfComp << endl;
}
20.7(桶排序)
#include <vector>
using namespace std;
class BucketSort
{
public:
BucketSort(int);
void displayElements() const;
void sort();
private:
int size;
vector< int > data;
vector< vector < int > > bucket;
void distributeElements(int);
void collectElements();
int numberOfDigits();
void zeroBucket();
};
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "BucketSort.h"
using namespace std;
BucketSort::BucketSort( int vectorSize )
{
size = ( vectorSize > 0 ? vectorSize : 10 );
srand( time( 0 ) );
for ( int i = 0; i < size; i++ )
data.push_back( 10 + rand() % 90 );
for ( int i = 0; i < 10; i++ )
bucket.push_back( vector < int >( size ) );
}
void BucketSort::displayElements() const
{
for ( int i = 0; i < size; i++ )
cout << data[ i ] << " ";
cout << endl;
}
void BucketSort::sort()
{
int totalDigits;
zeroBucket();
totalDigits = numberOfDigits();
for (int i = 1; i <= totalDigits; i++)
{
distributeElements(i);
collectElements();
if (i != totalDigits)
zeroBucket();
}
}
void BucketSort::distributeElements(int digit)
{
int divisor = 10;
int bucketNumber;
int elementNumber;
for (int i = 1; i < digit; ++i)
divisor *= 10;
for (int k = 0; k < size; ++k)
{
bucketNumber = (data[k] % divisor - data[k] %
(divisor / 10)) / (divisor / 10);
elementNumber = ++bucket[bucketNumber][0];
bucket[bucketNumber][elementNumber] = data[k];
}
}
void BucketSort::collectElements()
{
int subscript = 0;
for (int i = 0; i < 10; i++)
{
for (int j = 1; j <= bucket[i][0]; j++)
data[subscript++] = bucket[i][j];
}
}
int BucketSort::numberOfDigits()
{
int largest = data[0];
int digits = 0;
for (int i = 1; i < size; i++)
{
if (data[i] > largest)
largest = data[i];
}
while (largest != 0)
{
++digits;
largest /= 10;
}
return digits;
}
void BucketSort::zeroBucket()
{
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < size; j++)
bucket[i][j] = 0;
}
}
#include <iostream>
#include "BucketSort.h"
using namespace std;
int main()
{
BucketSort sortVector(12);
cout << "Vector elements in original order:\n";
sortVector.displayElements();
sortVector.sort();
cout << "\nVector elements in sorted order:\n";
sortVector.displayElements();
}
20.8(递归的线性查找法)
#include <iostream>
#include <vector>
using namespace std;
int recursiveLinearSearch( vector < int > &, int, int, int );
int main()
{
const int SIZE = 100;
vector < int > data(SIZE);
int searchKey;
int element;
for (int loop = 0; loop < SIZE; loop++)
data[loop] = 2 * loop;
cout << "Enter the integer search key: ";
cin >> searchKey;
element = recursiveLinearSearch(data, searchKey, 0, SIZE - 1);
if (element != -1)
cout << "Found value in element " << element << endl;
else
cout << "Value not found" << endl;
}
int recursiveLinearSearch(
vector < int >& array, int key, int low, int high)
{
if (array[low] == key)
return low;
else if (low == high)
return -1;
else
return recursiveLinearSearch(array, key, low + 1, high);
}
20.9(递归的二分查找法)
#include <vector>
using namespace std;
class BinarySearch
{
public:
BinarySearch(int);
int binarySearch(int) const;
void displayElements() const;
private:
int size;
vector< int > data;
void displaySubElements(int, int) const;
int recursiveBinarySearch(int, int, int) const;
};
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <algorithm>
#include "BinarySearch.h"
using namespace std;
BinarySearch::BinarySearch(int vectorSize)
{
size = (vectorSize > 0 ? vectorSize : 10);
srand(time(0));
for (int i = 0; i < size; i++)
data.push_back(10 + rand() % 90);
sort(data.begin(), data.end());
}
int BinarySearch::binarySearch(int searchElement) const
{
int low = 0;
int high = size - 1;
return recursiveBinarySearch(searchElement, low, high);
}
int BinarySearch::recursiveBinarySearch(
int searchElement, int low, int high) const
{
if (low > high)
return -1;
displaySubElements(low, high);
int middle = (low + high + 1) / 2;
for (int i = 0; i < middle; i++)
cout << " ";
cout << " * " << endl;
int location = -1;
if (searchElement == data[middle])
location = middle;
else if (searchElement < data[middle])
location = recursiveBinarySearch(searchElement, low, middle - 1);
else
location = recursiveBinarySearch(searchElement, middle + 1, high);
return location;
}
void BinarySearch::displayElements() const
{
displaySubElements(0, size - 1);
}
void BinarySearch::displaySubElements(int low, int high) const
{
for (int i = 0; i < low; i++)
cout << " ";
for (int i = low; i <= high; i++)
cout << data[i] << " ";
cout << endl;
}
#include <iostream>
#include "BinarySearch.h"
using namespace std;
int main()
{
int searchInt;
int position;
BinarySearch searchVector(15);
searchVector.displayElements();
cout << "\nPlease enter an integer value (-1 to quit): ";
cin >> searchInt;
cout << endl;
while (searchInt != -1)
{
position = searchVector.binarySearch(searchInt);
if (position == -1)
cout << "The integer " << searchInt << " was not found.\n";
else
cout << "The integer " << searchInt
<< " was found in position " << position << ".\n";
cout << "\n\nPlease enter an integer value (-1 to quit): ";
cin >> searchInt;
cout << endl;
}
}
20.10(快速排序算法)
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
#include <vector>
using namespace std;
void quickSortHelper( vector < int > &, int, int );
int partition( vector < int > &, int, int );
void swap( int * const, int * const );
int main()
{
const int MAX_NUMBER = 100;
const int SIZE = 10;
vector < int > vectorToBeSorted(SIZE);
int loop;
srand(time(0));
for (loop = 0; loop < SIZE; loop++)
vectorToBeSorted[loop] = rand() % MAX_NUMBER;
cout << "Initial vector values are:\n";
for (loop = 0; loop < SIZE; loop++)
cout << setw(4) << vectorToBeSorted[loop];
cout << "\n\n";
if (SIZE == 1)
cout << "Vector is sorted: " << vectorToBeSorted[0] << '\n';
else
{
quickSortHelper(vectorToBeSorted, 0, SIZE - 1);
cout << "The sorted vector values are:\n";
for (loop = 0; loop < SIZE; loop++)
cout << setw(4) << vectorToBeSorted[loop];
cout << endl;
}
}
void quickSortHelper(vector < int >& data, int first, int last)
{
int currentLocation;
if (first >= last)
return;
currentLocation = partition(data, first, last);
quickSortHelper(data, first, currentLocation - 1);
quickSortHelper(data, currentLocation + 1, last);
}
int partition(vector < int >& data, int left, int right)
{
int position = left;
while (true)
{
while (data[position] <= data[right] && position != right)
--right;
if (position == right)
return position;
if (data[position] > data[right])
{
swap(&data[position], &data[right]);
position = right;
}
while (data[left] <= data[position] && left != position)
++left;
if (position == left)
return position;
if (data[left] > data[position])
{
swap(&data[position], &data[left]);
position = left;
}
}
}
void swap(int* const ptr1, int* const ptr2)
{
int temp;
temp = *ptr1;
*ptr1 = *ptr2;
*ptr2 = temp;
}
第二十一章
21.7(简单加密)
a
#include <iostream>
#include <string>
using namespace std;
int main()
{
string m;
int key = 13;
cout << "Enter a string: ";
getline(cin, m);
string::iterator mi = m.begin();
while (mi != m.end())
{
*mi += key;
mi++;
}
cout << "\nEncrypted string is: " << m << endl;
}
b
#include <iostream>
#include <string>
using namespace std;
int main()
{
string m;
int key = 13;
cout << "Enter encrypted string: ";
getline(cin, m);
string::iterator mi = m.begin();
while (mi != m.end())
{
*mi -= key;
mi++;
}
cout << "\nDecrypted string is: " << m << endl;
}
21.8(使用字符串迭代器)
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s("abcdefghijklmnopqrstuvwxyz");
string::reverse_iterator re = s.rend();
string::reverse_iterator rb = s.rbegin();
cout << "Using rend() string is: ";
while (re >= s.rbegin())
{
cout << *re;
re--;
}
cout << "\nUsing rbegin() string is: ";
while (rb != s.rend())
{
cout << *rb;
rb++;
}
cout << endl;
}
21.9(以“r”或“ay"结尾的单词)
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s[5];
for (int i = 0; i < 5; i++)
{
cout << "Enter a word: ";
cin >> s[i];
}
for (int j = 0; j < 5; j++)
{
if (((s[j].rfind("ay") == s[j].length() - 2))
|| (s[j].rfind("r") == s[j].length() - 1))
cout << s[j] << endl;
}
}
21.10(字符串连接)
#include <iostream>
#include <string>
using namespace std;
int main()
{
string first;
string last;
cout << "Enter first name: ";
cin >> first;
cout << "Enter last name: ";
cin >> last;
first.append(" ").append(last);
cout << "The full name is: " << first << endl;
}
21.11(猜字游戏)
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
string response;
int w = 0;
const int WORDS = 4;
do
{
const char body[] = " o/|\\|/\\";
string words[WORDS] = {
"MACAW", "SADDLE", "TOASTER", "XENOCIDE" };
string xword(words[w].length(), '?');
string::iterator i;
string::iterator ix = xword.begin();
char letters[26] = { '\0' };
int n = 0;
int xcount = xword.length();
bool found = false;
bool solved = false;
int offset = 0;
int bodyCount = 0;
bool hung = false;
cout << "Guess the word: ";
for (unsigned loop = 0; loop < words[w].length(); loop++)
cout << "X";
do
{
cout << "\n\nGuess a letter (case does not matter): "
<< xword << "\n?";
char temp;
cin >> temp;
if (!isalpha(temp))
{
cout << "\nLETTERS ONLY PLEASE\n";
continue;
}
letters[n] = toupper(temp);
i = words[w].begin();
found = false;
offset = 0;
while (i != words[w].end())
{
if (*i == letters[n])
{
*(ix + offset) = *i;
found = true;
if (--xcount == 0)
solved = true;
}
i++;
offset++;
}
if (!found)
bodyCount++;
bool newline = false;
for (int q = 1; q <= bodyCount; q++)
{
if (q == 1 || q == 5 || q == 7)
{
newline = true;
cout << body[0];
}
else if (q == 4)
newline = true;
else
newline = false;
cout << body[q];
if (newline)
cout << '\n';
}
if (bodyCount == 7)
{
cout << "\n\n...GAME OVER...\n";
hung = true;
break;
}
cout << "\nYour guesses:\n";
for (int k = 0; k <= n; k++)
cout << setw(2) << letters[k];
n++;
} while (!solved);
cout << "\n\nWord: " << words[w] << "\n\n";
if (!hung)
cout << "\nCongratulations!!! You guessed "
<< "my word.\n";
if (w++ >= WORDS)
break;
cout << "Play again (yes/no)? ";
cin >> response;
} while (!response.compare("yes"));
cout << "\nThank you for playing hangman." << endl;
}
20.12(反序打印字符串)
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;
cout << "Enter a string: ";
getline(cin, s, '\n');
string::reverse_iterator r = s.rbegin();
while (r != s.rend())
{
*r = (isupper(*r) ? tolower(*r) : toupper(*r));
cout << *(r++);
}
cout << endl;
}
20.13(按字母表排序动物名字)
#include <iostream>
#include <string>
using namespace std;
void output( const string *, const int );
void quickSort( string [], int, int );
int partition( string [], int, int );
int main()
{
const int SIZE = 19;
string animals[] = { "Macaw", "Lion", "Tiger", "Bear", "Toucan",
"Zebra", "Puma", "Cat", "Yak", "Boar", "Fox", "Ferret",
"Crocodile", "Alligator", "Elk", "Ox", "Horse", "Eagle", "Hawk" };
cout << "before:";
output(animals, SIZE);
quickSort(animals, 0, SIZE);
cout << "\nafter:";
output(animals, SIZE);
}
void output(const string* const ani, const int length)
{
for (int j = 0; j < length; ++j)
cout << (j % 10 ? ' ' : '\n') << ani[j];
cout << endl;
}
void quickSort(string a[], int first, int last)
{
int currentLocation;
if (first >= last)
return;
currentLocation = partition(a, first, last);
quickSort(a, first, currentLocation - 1);
quickSort(a, currentLocation + 1, last);
}
int partition(string b[], int left, int right)
{
int pos = left;
while (true)
{
while (b[pos] <= b[right] && pos != right)
right--;
if (pos == right)
return pos;
if (b[pos] > b[right])
{
b[pos].swap(b[right]);
pos = right;
}
while (b[left] <= b[pos] && pos != left)
left++;
if (pos == left)
return pos;
if (b[left] > b[pos])
{
b[pos].swap(b[left]);
pos = left;
}
}
}
21.19(从字符串中删除字符序列)
#include <iostream>
#include <string>
using namespace std;
void deleteBy( string&, string );
int main()
{
string s;
cout << "Enter a word: ";
cin >> s;
deleteBy(s, "by");
deleteBy(s, "BY");
cout << s << endl;
}
void deleteBy(string& sRef, string z)
{
int x = sRef.find(z);
while (x <= sRef.length())
{
sRef.erase(x, 2);
x = sRef.find(z);
}
}
21.20(使用迭代器反序字符串)
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;
cout << "Enter a string: ";
getline(cin, s, '\n');
string::reverse_iterator rb = s.rbegin();
while (rb != s.rend())
{
cout << *rb;
++rb;
}
cout << endl;
}
21.21(按递归的方法使用迭代器反序字符串)
#include <iostream>
#include <string>
using namespace std;
void printBackward(const string::reverse_iterator,
string::reverse_iterator);
int main()
{
string s;
cout << "Enter a string: ";
getline(cin, s);
string::reverse_iterator r = s.rend();
printBackward(s.rbegin(), r - 1);
cout << endl;
}
void printBackward(const string::reverse_iterator s,
string::reverse_iterator rb)
{
if (rb == s - 1)
return;
printBackward(s, rb - 1);
cout << *rb;
}
第二十二章
22.5(洗牌和发牌)
struct BitCard
{
unsigned face : 4;
unsigned suit : 2;
unsigned color : 1;
};
class DeckOfCards
{
public:
DeckOfCards();
void shuffle();
void deal();
private:
BitCard deck[52];
};
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include "DeckOfCards.h"
using namespace std;
DeckOfCards::DeckOfCards()
{
for (int i = 0; i <= 51; i++)
{
deck[i].face = i % 13;
deck[i].suit = i / 13;
deck[i].color = i / 26;
}
}
void DeckOfCards::shuffle()
{
for (int i = 0; i < 52; i++)
{
int j = rand() % 52;
BitCard temp = deck[i];
deck[i] = deck[j];
deck[j] = temp;
}
}
void DeckOfCards::deal()
{
char* face[] = { "Ace", "Deuce", "Three", "Four", "Five", "Six",
"Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King" };
char* suit[] = { "Hearts", "Diamonds", "Clubs", "Spades" };
char* color[] = { "Red", "Black" };
for (int i = 0; i < 52; i++)
{
cout << right << setw(5) << color[deck[i].color] << ": "
<< setw(8) << face[deck[i].face] << " of "
<< left << setw(8) << suit[deck[i].suit]
<< ((i + 1) % 2 ? '\t' : '\n');
}
}
#include "DeckOfCards.h"
int main()
{
DeckOfCards deckOfCards;
deckOfCards.shuffle();
deckOfCards.deal();
}
22.6(移动并打印整数)
#include <iostream>
#include <iomanip>
using namespace std;
void displayBits( unsigned );
int main()
{
unsigned val;
cout << "Enter an integer: ";
cin >> val;
cout << "\nBefore right shifting 4 bits is:\n";
displayBits(val);
cout << "After right shifting 4 bits is:\n";
displayBits(val >> 4);
}
void displayBits(unsigned value)
{
const int SHIFT = 8 * sizeof(unsigned) - 1;
const unsigned MASK = 1 << SHIFT;
cout << setw(7) << value << " = ";
for (unsigned c = 1; c <= SHIFT + 1; c++)
{
cout << (value & MASK ? '1' : '0');
value <<= 1;
if (c % 8 == 0)
cout << ' ';
}
cout << endl;
}
22.7(通过位移动来操作)
#include <iostream>
#include <iomanip>
using namespace std;
void displayBits( unsigned );
unsigned power2( unsigned, unsigned );
int main()
{
unsigned number;
unsigned pow;
unsigned result;
cout << "Enter two integers: ";
cin >> number >> pow;
cout << "\nnumber:\n";
displayBits(number);
cout << "\npower:\n";
displayBits(pow);
result = power2(number, pow);
cout << '\n' << number << " * 2^" << pow << " = " << result << '\n';
displayBits(result);
}
unsigned power2( unsigned n, unsigned p )
{
return n << p;
}
void displayBits(unsigned value)
{
const int SHIFT = 8 * sizeof(unsigned) - 1;
const unsigned MASK = 1 << SHIFT;
cout << setw(7) << value << " = ";
for (unsigned c = 1; c <= SHIFT + 1; c++)
{
cout << (value & MASK ? '1' : '0');
value <<= 1;
if (c % 8 == 0)
cout << ' ';
}
cout << endl;
}
22.8(将字符打包成无符号整型)
#include <iostream>
#include <iomanip>
using namespace std;
unsigned packCharacters(char, char);
void displayBits(unsigned);
int main()
{
char a;
char b;
unsigned result;
cout << "Enter two characters: ";
cin >> a >> b;
cout << "\n\'" << a << '\'' << " in bits as an unsigned integer is:\n";
displayBits(a);
cout << '\'' << b << '\'' << " in bits as an unsigned integer is:\n";
displayBits(b);
result = packCharacters(a, b);
cout << "\n\'" << a << '\'' << " and " << '\'' << b << '\''
<< " packed in an unsigned integer:\n";
displayBits(result);
}
unsigned packCharacters(char x, char y)
{
unsigned pack = x;
pack <<= 8;
pack |= y;
return pack;
}
void displayBits(unsigned value)
{
const int SHIFT = 8 * sizeof(unsigned) - 1;
const unsigned MASK = 1 << SHIFT;
cout << setw(7) << value << " = ";
for (unsigned c = 1; c <= SHIFT + 1; c++)
{
cout << (value & MASK ? '1' : '0');
value <<= 1;
if (c % 8 == 0)
cout << ' ';
}
cout << endl;
}
22.9(将字符从无符号整型中解包)
#include <iostream>
#include <iomanip>
using namespace std;
void unpackCharacters(char* const, char* const, unsigned);
void displayBits(unsigned);
int main()
{
char a;
char b;
unsigned packed = 16706;
cout << "The packed character representation is:\n";
displayBits(packed);
unpackCharacters(&a, &b, packed);
cout << "\nThe unpacked characters are \'" << a << "\' and \'" << b
<< "\'\n";
displayBits(a);
displayBits(b);
}
void unpackCharacters(char* const aPtr, char* const bPtr,
unsigned pack)
{
unsigned mask1 = 65280;
unsigned mask2 = 255;
*aPtr = static_cast<char>((pack & mask1) >> 8);
*bPtr = static_cast<char>(pack & mask2);
}
void displayBits(unsigned value)
{
const int SHIFT = 8 * sizeof(unsigned) - 1;
const unsigned MASK = 1 << SHIFT;
cout << setw(7) << value << " = ";
for (unsigned c = 1; c <= SHIFT + 1; c++)
{
cout << (value & MASK ? '1' : '0');
value <<= 1;
if (c % 8 == 0)
cout << ' ';
}
cout << endl;
}
22.10(反转比特位)
#include <iostream>
#include <iomanip>
using namespace std;
void reverseBits( unsigned * const );
void displayBits( unsigned );
int main()
{
unsigned a;
cout << "Enter an unsigned integer: ";
cin >> a;
cout << "\nBefore bits are reversed:\n";
displayBits(a);
reverseBits(&a);
cout << "\nAfter bits are reversed:\n";
displayBits(a);
}
void reverseBits(unsigned* const vPtr)
{
const int SHIFT = 8 * sizeof(unsigned) - 1;
const unsigned MASK = 1;
unsigned value = *vPtr;
for (int i = 0; i <= SHIFT; i++)
{
*vPtr <<= 1;
*vPtr |= (value & MASK);
value >>= 1;
}
}
void displayBits(unsigned value)
{
const int SHIFT = 8 * sizeof(unsigned) - 1;
const unsigned MASK = 1 << SHIFT;
cout << setw(7) << value << " = ";
for (unsigned c = 1; c <= SHIFT + 1; c++)
{
cout << (value & MASK ? '1' : '0');
value <<= 1;
if (c % 8 == 0)
cout << ' ';
}
cout << endl;
}
22.14
#include <iostream>
#include <cctype>
using namespace std;
const int SIZE = 100;
int main()
{
char s[SIZE];
int i;
cout << "Enter a line of text:\n";
cin.getline(s, SIZE);
cout << "\nThe line in uppercase is:\n";
for (i = 0; s[i] != '\0'; ++i)
cout << static_cast<char>(toupper(s[i]));
cout << "\n\nThe line in lowercase is:\n";
for (i = 0; s[i] != '\0'; ++i)
cout << static_cast<char>(tolower(s[i]));
cout << endl;
}
22.15(将字符串转化为整型)
#include <iostream>
#include <cstdlib>
using namespace std;
const int SIZE = 6;
int main()
{
char stringValue[SIZE];
int sum = 0;
for (int i = 1; i <= 4; ++i)
{
cout << "Enter an integer string: ";
cin >> stringValue;
sum += atoi(stringValue);
}
cout << "The total of the values is " << sum << endl;
}
22.16(将字符串转化位浮点数)
#include <iostream>
#include <iomanip>
#include <cstdlib>
using namespace std;
const int SIZE = 15;
int main()
{
char stringValue[SIZE];
double sum = 0.0;
for (int i = 1; i <= 4; i++)
{
cout << "Enter a floating-point value: ";
cin >> stringValue;
sum += atof(stringValue);
}
cout << fixed << "\nThe total of the values is " << setprecision(3)
<< sum << endl;
}
22.17(搜索子串)
#include <iostream>
#include <cstring>
using namespace std;
const int SIZE1 = 80;
const int SIZE2 = 15;
int main()
{
char text[SIZE1];
char search[SIZE2];
char* searchPtr;
cout << "Enter a line of text:\n";
cin.get(text, SIZE1);
cout << "\nEnter a search string: ";
cin >> search;
searchPtr = strstr(text, search);
if (searchPtr)
{
cout << "\nThe remainder of the line beginning with\n"
<< "the first occurrence of \"" << search << "\":\n"
<< searchPtr << '\n';
searchPtr = strstr(searchPtr + 1, search);
if (searchPtr)
cout << "\nThe remainder of the line beginning with"
<< "\nthe second occurrence of \"" << search << "\":\n"
<< searchPtr << '\n';
else
cout << "\nThe search string appeared only once.\n";
}
else
cout << "\"" << search << "\" not found.\n";
}
22.18(搜索子串)
#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;
const int SIZE1 = 80;
const int SIZE2 = 20;
int main()
{
char text[3][SIZE1];
char search[SIZE2];
char* searchPtr;
int count = 0;
int i;
cout << "Enter three lines of text:\n";
for (i = 0; i <= 2; i++)
cin.getline(&text[i][0], SIZE1);
for (i = 0; i <= 2; i++)
for (int j = 0; text[i][j] != '\0'; j++)
{
char c = static_cast<char>(tolower(text[i][j]));
text[i][j] = c;
}
cout << "\nEnter a search string: ";
cin >> search;
for (i = 0; i <= 2; i++)
{
searchPtr = &text[i][0];
while (searchPtr = strstr(searchPtr, search))
{
++count;
++searchPtr;
}
}
cout << "\nThe total number of occurrences of \"" << search
<< "\" in the text is: " << count << endl;
}
22.19(搜索字符)
#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;
const int SIZE = 80;
int main()
{
char text[3][SIZE];
char search;
char* searchPtr;
int count = 0;
int i;
cout << "Enter three lines of text:\n";
for (i = 0; i <= 2; i++)
cin.getline(&text[i][0], SIZE)
for (i = 0; i <= 2; i++)
for (int j = 0; text[i][j] != '\0'; j++)
{
char c = static_cast<char>(tolower(text[i][j]));
text[i][j] = c;
}
cout << "\nEnter a search character: ";
cin >> search;
for (i = 0; i <= 2; i++)
{
searchPtr = &text[i][0];
while (searchPtr = strchr(searchPtr, search))
{
++count;
++searchPtr;
}
}
cout << "\nThe total number of occurrences of \'" << search
<< "\' in the text is: " << count << endl;
}
22.20(搜索字符)
#include <iostream>
#include <iomanip>
#include <cstring>
#include <cctype>
using namespace std;
const int SIZE1 = 80;
const int SIZE2 = 26;
int main()
{
char text[3][SIZE1];
char* searchPtr;
int characters[SIZE2] = { 0 };
cout << "Enter three lines of text:\n";
for (int i = 0; i <= 2; i++)
cin.getline(&text[i][0], SIZE1);
for (int k = 0; k <= 2; k++)
for (int j = 0; text[k][j] != '\0'; j++)
{
char c = static_cast<char>(tolower(text[k][j]));
text[k][j] = c;
}
for (int q = 0; q < SIZE2; q++)
{
for (int j = 0; j <= 2; j++)
{
searchPtr = &text[j][0];
while (searchPtr = strchr(searchPtr, 'a' + q))
{
characters[q]++;
searchPtr++;
}
}
}
cout << "\nThe total number of occurrences of each character:\n";
for (int w = 0; w < SIZE2; w++)
cout << setw(3) << static_cast<char>('a' + w) << ':'
<< setw(3) << characters[w] << '\n';
}
22.22(以b开头的字符串)
#include <iostream>
using namespace std;
const int SIZE = 20;
int main()
{
char array[5][SIZE];
int i;
for (i = 0; i <= 4; i++)
{
cout << "Enter a string: ";
cin.getline(&array[i][0], SIZE);
}
cout << "\nThe strings starting with 'b' are:\n";
for (i = 0; i <= 4; i++)
if (array[i][0] == 'b')
cout << &array[i][0] << '\n';
}
22.23(以ED结尾的字符串)
#include <iostream>
#include <cstring>
using namespace std;
const int SIZE = 20;
int main()
{
int length, i;
char array[5][SIZE];
for (i = 0; i <= 4; i++)
{
cout << "Enter a string: ";
cin.getline(&array[i][0], SIZE);
}
cout << "\nThe strings ending with \"ED\" are:\n";
for (i = 0; i <= 4; i++)
{
length = strlen(&array[i][0]);
if (strcmp(&array[i][length - 2], "ED") == 0)
cout << &array[i][0] << '\n';
}
}
22.24(打印给定ASCII码的字符)
a
#include <iostream>
using namespace std;
int main()
{
int c;
cout << "Enter an ASCII character code (-1 to end): ";
cin >> c;
while (c != -1)
{
if (c >= 0 && c <= 255)
cout << "The corresponding character is '"
<< static_cast<char> (c) << "\'\n";
else
cout << "Invalid character code\n";
cout << "\nEnter an ASCII character code (-1 to end): ";
cin >> c;
}
}
b
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
for (int c = 0; c <= 255; c++)
{
if (c % 7 == 0)
cout << '\n';
cout << setw(6) << c << setw(3) << static_cast<char> (c);
}
cout << endl;
}
22.30(字符串比较)
#include <iostream>
#include <cstring>
using namespace std;
const int SIZE = 20;
int main()
{
char string1[SIZE];
char string2[SIZE];
int result;
cout << "Enter two strings: ";
cin >> string1 >> string2;
result = strcmp(string1, string2);
if (result > 0)
cout << '\"' << string1 << '\"' << " is greater than \""
<< string2 << '\"' << endl;
else if (result == 0)
cout << '\"' << string1 << '\"' << " is equal to \"" << string2
<< '\"' << endl;
else
cout << '\"' << string1 << '\"' << " is less than \"" << string2
<< '\"' << endl;
}
22.31(字符串比较)
#include <iostream>
#include <cstring>
using namespace std;
const int SIZE = 20;
int main()
{
char string1[SIZE];
char string2[SIZE];
int result;
int compareCount;
cout << "Enter two strings: ";
cin >> string1 >> string2;
cout << "How many characters should be compared: ";
cin >> compareCount; \
result = strncmp(string1, string2, compareCount);
if (result > 0)
cout << '\"' << string1 << "\" is greater than \"" << string2
<< "\" up to " << compareCount << " characters\n";
else if (result == 0)
cout << '\"' << string1 << "\" is equal to \"" << string2
<< "\" up to " << compareCount << " characters\n";
else
cout << '\"' << string1 << "\" is less than \"" << string2
<< "\" up to " << compareCount << " characters\n";
cout << endl;
}
23.32(随机创造句子)
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cctype>
using namespace std;
const int SIZE = 100;
int main()
{
const char* article[] = { "the", "a", "one", "some", "any" };
const char* noun[] = { "boy", "girl", "dog", "town", "car" };
const char* verb[] = { "drove", "jumped", "ran", "walked", "skipped" };
const char* preposition[] = { "to", "from", "over", "under", "on" };
char sentence[SIZE] = "";
srand(time(0));
for (int i = 1; i <= 20; ++i)
{
strcat(sentence, article[rand() % 5]);
strcat(sentence, " ");
strcat(sentence, noun[rand() % 5]);
strcat(sentence, " ");
strcat(sentence, verb[rand() % 5]);
strcat(sentence, " ");
strcat(sentence, preposition[rand() % 5]);
strcat(sentence, " ");
strcat(sentence, article[rand() % 5]);
strcat(sentence, " ");
strcat(sentence, noun[rand() % 5]);
cout << static_cast<char> (toupper(sentence[0]))
<< &sentence[1] << ".\n";
sentence[0] = '\0';
}
cout << endl;
}
22.34(儿童黑话游戏)
#include <iostream>
#include <cstring>
using namespace std;
const int SIZE = 80;
void printLatinWord(char const* const);
int main()
{
char sentence[SIZE];
char* tokenPtr;
cout << "Enter a sentence:\n";
cin.getline(sentence, SIZE);
cout << "\nThe sentence in Pig Latin is:\n";
tokenPtr = strtok(sentence, " .,;");
while (tokenPtr)
{
printLatinWord(tokenPtr);
tokenPtr = strtok(0, " .,;");
if (tokenPtr)
cout << ' ';
}
cout << '.' << endl;
}
void printLatinWord(char const* const wordPtr)
{
int len = strlen(wordPtr);
for (int i = 1; i < len; i++)
cout << *(wordPtr + i);
cout << *wordPtr << "ay";
}
22.35(记号化电话号码)
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
const int SIZE1 = 20;
const int SIZE2 = 10;
char p[SIZE1];
char phoneNumber[SIZE2] = { '\0' };
char* tokenPtr;
char* areaCode;
char* phone;
cout << "Enter a phone number in the form (555) 555-5555:\n";
cin.getline(p, SIZE1);
areaCode = strtok(p, "()");
tokenPtr = strtok(0, "-");
strcpy(phoneNumber, tokenPtr);
tokenPtr = strtok(0, "");
strcat(phoneNumber, tokenPtr);
phone = phoneNumber;
cout << "\nThe area code is " << areaCode
<< "\nThe phone number is " << phone << endl;
}
22.36(记号化并反转一个句子)
#include <iostream>
#include <cstring>
using namespace std;
void reverseTokens(char* const);
int main()
{
const int SIZE = 80;
char text[SIZE];
cout << "Enter a line of text:\n";
cin.getline(text, SIZE);
reverseTokens(text);
cout << endl;
}
void reverseTokens(char* const sentence)
{
char* pointers[50];
char* temp;
int count = 0;
temp = strtok(sentence, " ");
while (temp)
{
pointers[count++] = temp;
temp = strtok(0, " ");
}
cout << "\nThe tokens in reverse order are:\n";
for (int i = count - 1; i >= 0; i--)
cout << pointers[i] << ' ';
}
22.37(将一个句子按照字母顺序排列)
#include <iostream>
#include <cstring>
using namespace std;
const int SIZE = 50;
void insertionSort(char[][SIZE]);
int main()
{
char array[10][SIZE];
int i;
for (i = 0; i < 10; i++)
{
cout << "Enter a string: ";
cin >> &array[i][0];
}
insertionSort(array);
cout << "\nThe strings in sorted order are:\n";
for (i = 0; i < 10; i++)
cout << &array[i][0] << endl;
}
void insertionSort(char a[][SIZE])
{
char insert[SIZE];
for (int next = 1; next < 10; next++)
{
strcpy(insert, a[next]);
int moveItem = next;
while (moveItem > 0 && strcmp(a[moveItem - 1], insert) > 0)
{
strcpy(a[moveItem], a[moveItem - 1]);
moveItem--;
}
strcpy(a[moveItem], insert);
}
}
22.38(编写你自己的字符串复制和连接函数)
#include <iostream>
using namespace std;
char* stringCopy1(char*, const char*);
char* stringCopy2(char*, const char*);
char* stringNCopy1(char*, const char*, unsigned);
char* stringNCopy2(char*, const char*, unsigned);
char* stringCat1(char*, const char*);
char* stringCat2(char*, const char*);
char* stringNCat1(char*, const char*, unsigned);
char* stringNCat2(char*, const char*, unsigned);
int main()
{
int n = 4;
char string1[100];
char string2[100];
cout << "Enter a string: ";
cin >> string2;
cout << "Copied string returned from stringCopy1 is "
<< stringCopy1(string1, string2)
<< "\nCopied string returned from stringCopy2 is "
<< stringCopy2(string1, string2);
cout << "\nCopied " << n << " elements returned from stringNCopy1 is "
<< stringNCopy1(string1, string2, n)
<< "\nCopied " << n << " elements returned from stringNCopy2 is "
<< stringNCopy2(string1, string2, n);
cout << "\nConcatenated string returned from stringCat1 is "
<< stringCat1(string1, string2)
<< "\nConcatenated string returned from stringCat2 is "
<< stringCat2(string1, string2);
cout << "\nConcatenated string returned from stringNCat1 is "
<< stringNCat1(string1, string2, n)
<< "\nConcatenated string returned from stringNCat2 is "
<< stringNCat2(string1, string2, n) << endl;
}
char* stringCopy1(char* s1, const char* s2)
{
for (int sub = 0; s1[sub] = s2[sub]; sub++)
;
return s1;
}
char* stringCopy2(char* s1, const char* s2)
{
char* ptr = s1;
for (; *s1 = *s2; s1++, s2++)
;
return ptr;
}
char* stringNCopy1(char* s1, const char* s2, unsigned n)
{
unsigned c;
for (c = 0; c < n && (s1[c] = s2[c]); c++)
;
s1[c] = '\0';
return s1;
}
char* stringNCopy2(char* s1, const char* s2, unsigned n)
{
char* ptr = s1;
for (unsigned c = 0; c < n; c++, s1++, s2++)
*s1 = *s2;
*s1 = '\0';
return ptr;
}
char* stringCat1(char* s1, const char* s2)
{
int x;
for (x = 0; s1[x] != '\0'; x++)
;
for (int y = 0; s1[x] = s2[y]; x++, y++)
;
return s1;
}
char* stringCat2(char* s1, const char* s2)
{
char* ptr = s1;
for (; *s1 != '\0'; s1++)
;
for (; *s1 = *s2; s1++, s2++)
;
return ptr;
}
char* stringNCat1(char* s1, const char* s2, unsigned n)
{
int x;
for (x = 0; s1[x] != '\0'; x++)
;
for (unsigned y = 0; y < n && (s1[x] = s2[y]); x++, y++)
;
s1[x] = '\0';
return s1;
}
char* stringNCat2(char* s1, const char* s2, unsigned n)
{
char* ptr = s1;
for (; *s1 != '\0'; s1++)
;
for (unsigned c = 0; c < n && (*s1 = *s2); s1++, s2++)
;
*s1 = '\0';
return ptr;
}
22.39(编写你自己的字符串比较函数)
#include <iostream>
using namespace std;
int stringCompare1(const char*, const char*);
int stringCompare2(const char*, const char*);
int stringNCompare1(const char*, const char*, unsigned);
int stringNCompare2(const char*, const char*, unsigned);
int main()
{
char string1[100], string2[100];
unsigned n = 3;
cout << "Enter two strings: ";
cin >> string1 >> string2;
cout << "The value returned from stringCompare1(\"" << string1
<< "\", \"" << string2 << "\") is "
<< stringCompare1(string1, string2)
<< "\nThe value returned from stringCompare2(\"" << string1
<< "\", \"" << string2 << "\") is "
<< stringCompare2(string1, string2) << '\n';
cout << "\nThe value returned from stringNCompare1(\"" << string1
<< "\", \"" << string2 << "\", " << n << ") is "
<< stringNCompare1(string1, string2, n)
<< "\nThe value returned from stringNCompare2(\"" << string1
<< "\", \"" << string2 << "\", " << n << ") is "
<< stringNCompare2(string1, string2, n) << endl;
}
int stringCompare1(const char* s1, const char* s2)
{
int sub;
for (sub = 0; s1[sub] == s2[sub]; sub++)
;
sub--;
if (s1[sub] == '\0' && s2[sub] == '\0')
return 0;
else if (s1[sub] < s2[sub])
return -1;
else
return 1;
}
int stringCompare2(const char* s1, const char* s2)
{
for (; *s1 == *s2; s1++, s2++)
;
s1--;
s2--;
if (*s1 == '\0' && *s2 == '\0')
return 0;
else if (*s1 < *s2)
return -1;
else
return 1;
}
int stringNCompare1(const char* s1, const char* s2, unsigned n)
{
unsigned sub;
for (sub = 0; sub < n && (s1[sub] == s2[sub]); sub++)
;
sub--;
if (s1[sub] == s2[sub])
return 0;
else if (s1[sub] < s2[sub])
return -1;
else
return 1;
}
int stringNCompare2(const char* s1, const char* s2, unsigned n)
{
for (unsigned c = 0; c < n && (*s1 == *s2); c++, s1++, s2++)
;
s1--;
s2--;
if (*s1 == *s2)
return 0;
else if (*s1 < *s2)
return -1;
else
return 1;
}
22.40(编写你自己的字符串长度函数)
#include <iostream>
using namespace std;
unsigned long stringLength1( const char * );
unsigned long stringLength2( const char * );
int main()
{
char string[100];
cout << "Enter a string: ";
cin >> string;
cout << "\nAccording to stringLength1 the string length is: "
<< stringLength1(string)
<< "\nAccording to stringLength2 the string length is: "
<< stringLength2(string) << endl;
}
unsigned long stringLength1(const char* sPtr)
{
int length;
for (length = 0; sPtr[length] != '\0'; length++)
;
return length;
}
unsigned long stringLength2(const char* sPtr)
{
int length;
for (length = 0; *sPtr != '\0'; sPtr++, length++)
;
return length;
}
22.41(文本分析)
a
#include <iostream>
#include <iomanip>
#include <cctype>
using namespace std;
const int SIZE = 80;
int main()
{
char letters[26] = {};
char text[3][SIZE];
char i;
cout << "Enter three lines of text:\n";
for (i = 0; i <= 2; ++i)
cin.getline(&text[i][0], SIZE);
for (i = 0; i <= 2; i++)
for (int j = 0; text[i][j] != '\0'; j++)
if (isalpha(text[i][j]))
letters[tolower(text[i][j]) - 'a']++;
cout << "\nTotal letter counts:\n";
for (i = 0; i <= 25; i++)
cout << setw(3) << static_cast<char> ('a' + i) << ':'
<< setw(3) << static_cast<int> (letters[i]) << endl;
}
b
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
const int SIZE = 80;
char text[3][SIZE];
char* temp;
int lengths[20] = {};
int i;
cout << "Enter three lines of text:\n";
for (i = 0; i <= 2; i++)
cin.getline(&text[i][0], SIZE);
for (i = 0; i <= 2; i++)
{
temp = strtok(&text[i][0], ". \n");
while (temp)
{
lengths[strlen(temp)]++;
temp = strtok(0, ". \n");
}
}
cout << '\n';
for (i = 1; i <= 19; i++)
if (lengths[i])
cout << lengths[i] << " word(s) of length: " << i << endl;
}
c
#include <iostream>
#include <cstring>
using namespace std;
const int SIZE = 80;
int main()
{
char text[3][SIZE];
char* temp;
char words[100][20] = { "" };
int count[100] = {};
int i;
cout << "Enter three lines of text:\n";
for (i = 0; i <= 2; i++)
cin.getline(&text[i][0], SIZE);
for (i = 0; i <= 2; i++)
{
temp = strtok(&text[i][0], ". \n");
while (temp)
{
int j;
for (j = 0; words[j][0] &&
strcmp(temp, &words[j][0]) != 0; j++)
;
count[j]++;
if (!words[j][0])
strcpy(&words[j][0], temp);
temp = strtok(0, ". \n");
}
}
cout << '\n';
for (int k = 0; words[k][0] != '\0' && k <= 99; k++)
cout << "\"" << &words[k][0] << "\" appeared " << count[k]
<< " time(s)\n";
cout << endl;
}
第二十三章
23.4(命名空间Currency)
#include <iostream>
using namespace std;
namespace Currency
{
enum Money {
ONE = 1, TWO, FIVE = 5, TEN = 10,
TWENTY = 20, FIFTY = 50, HUNDRED = 100
};
}
int main()
{
using Currency::FIVE;
cout << "FIVE's value is: " << FIVE << endl;
}
23.7(修改const变量)
#include <iostream>
using namespace std;
int main()
{
const char c = 'A';
const char* ptr = &c;
cout << "c is " << *ptr;
*const_cast<char*> (ptr) = 'Z';
cout << "\nc is " << *ptr << endl;
}
23.9(virtual基类)
#include <iostream>
using namespace std;
class Base
{
public:
Base(int n)
{
num = n;
}
void print()
{
cout << num;
}
private:
int num;
};
class D1 : virtual public Base
{
public:
D1() : Base(3) {}
};
class D2 : virtual public Base
{
public:
D2() : Base(5) {}
};
class Multi : public D1, D2
{
public:
Multi(int a) : Base(a) {}
};
int main()
{
Multi m(9);
m.print();
cout << endl;
}