编写一个函数searchName,用于搜索以特定字母开头的所有名称。将下标存储在名为searchResults的数组中,该数组最多可存储20个元素,然后在屏幕上显示该列表。
以下是名称列表:
John P. 玛丽Q. 山姆T. 汤姆L. 丽莎O. 特蕾莎·A 彼得B. 哈里斯W. 玛西亚D. 约翰G. 劳伦斯F. 阿明C. 杰弗里N. 玛丽亚Z. Cuong N. 菲拉赫 克拉克 佩德罗J. 杰米O. 凯文Y。
我的代码:
void searchName(string n[], int lsize){
int searchcount = 0;
if(searchString[0] == n[i][0]){
searchResults[searchcount] = 1;
}
答案 0 :(得分:0)
#include <iostream>
using namespace std;
//an index used to properly store new letters in an array
int nextPosition;
//the maximum length the array can be
const int LIST_LENGTH = 20;
//an array to store unique letters
char searchResults[LIST_LENGTH];
//an array to store each letters count
int searchCount[LIST_LENGTH];
// Note: because ^these variables are defined
// outside any function they can be used anywhere in the file
void searchName(string name) {
//a 'flag' is used to tell if an entry for a letter has been recorded
bool noEntryFound = true;
//search unique letters for a match
for (int j = 0; j < nextPosition; j++){
//if the letter has been added already, increment it
if ( searchResults[j] == name[0] ){
searchCount[j] += 1;
//found an entry, so this flag is alternated,
// stopping more than 1 entry for the letter being added to array
noEntryFound = false;
//first letter is already in the array so breaking
// the loop saves searching the rest of the array
break;
}
}
//if the array has been searched
//and the letter wasn't found, add it, increment it
if (noEntryFound == true){
//store new letter, increment its count
searchResults[nextPosition] = name[0];
searchCount[nextPosition] += 1;
//increment the position that new items get added to the array at
nextPosition++;
}
}
int main(){
//the array of names of length 20 (LENGTH)
string names[LIST_LENGTH] = {
"John P.", "Mary Q.", "Sam T.",
"Tom L.","Lisa O.", "Teresa A.",
"Peter B.", "Harris W.", "Marcia D.",
"John G.", "Lawrence F.", "Amin C.","Jeffrey N.",
"Maria Z.", "Cuong N.","Fila H.", "Clark R.",
"Pedro J.","Jamie O.", "Kevin Y."
};
//iterate over all names as input for searchName
for (int i=0; i < LIST_LENGTH; i++){
searchName(names[i]);
}
//finally, print each letter and its equivalent count
for (int k=0; k<nextPosition; k++){
cout << searchResults[k] << " : " << searchCount[k] << endl;
}
return 1;
}