📄 prog9_08.cpp
字号:
// Program 9.8 Sorting strings recursively
#include <iostream>
#include <string>
using std::cout;
using std::cin;
using std::endl;
using std::string;
// Function prototypes
void swap(string* pStr[], int first, int second);
void sort(string* pStr[], int start, int end);
int count_words(const string& text, const string& separators);
void extract_words(string* pStr[], const string& text,
const string& separators);
void show_words(string* pStr[], int count);
int main() {
string text; // The string to be sorted
const string separators = " ,.\"\n"; // Word delimiters
// Read the string to be searched from the keyboard
cout << endl << "Enter a string terminated by #:" << endl;
getline(cin, text, '#');
int word_count = count_words(text, separators); // Get count of words
if(0 == word_count) {
cout << endl << "No words in text." << endl;
return 0;
}
string** pWords = new string*[word_count]; // Array of pntrs to words
extract_words(pWords, text, separators);
sort(pWords, 0, word_count-1); // Sort the words
show_words(pWords, word_count); // Output the words
// Delete words from free store
for(int i = 0 ; i<word_count ; i++)
delete pWords[i];
// Now delete the array of pointers
delete[] pWords;
return 0;
}
// Swap address at position first with address at position second
void swap(string* pStr[], int first, int second) {
string* temp = pStr[first];
pStr[first] = pStr[second];
pStr[second] = temp;
}
// Sort strings in ascending sequence
// Addresses of words to be sorted are from pStr[start] to pStr[end]
void sort(string* pStr[], int start, int end) {
// start index must be less than end index for 2 or more elements
if(!(start<end))
return; // Less than 2 elements
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -