C++ 查找多个字符串中最小字符串 - 代码示例及优化
#include
void find(char *name[], int n, int *p) { int minIndex = 0; for(int i = 1; i < n; i++) { if(strcmp(name[i], name[minIndex]) < 0) { minIndex = i; } } *p = minIndex; }
int main() { const int MAX_N = 100; // 最多输入100个字符串 char *name[MAX_N]; // 字符串指针数组 int n = 0; // 实际输入的字符串个数 char str[7]; // 用于输入字符串的字符数组 while(true) { cin >> str; if(strcmp(str, '####') == 0) { // 输入结束 break; } name[n] = new char[7]; // 动态分配内存 strcpy(name[n], str); // 将输入的字符串拷贝到动态分配的内存中 n++; } int minIndex; find(name, n, &minIndex); // 查找最小字符串 cout << name[minIndex] << endl; // 输出最小字符串 // 释放动态分配的内存 for(int i = 0; i < n; i++) { delete[] name[i]; } return 0; }
原文地址: https://www.cveoy.top/t/topic/ojLx 著作权归作者所有。请勿转载和采集!