#include <iostream> using namespace std; void findcount(int arr[], int size) { bool visited[size]; for (int i = 0; i < size; ++i) visited[i] = false; //初始化 cout << "元素 出现次数 下标位置" << endl; for (int i = 0; i < size; ++i) { if (!visited[i]) { //未被处理 int count = 1; string string1 = to_string(i); //转化为文本格式 visited[i] = true; for (int j = i + 1; j < size; ++j) { if (arr[j] == arr[i]) { visited[j] = true; count++; string1 += ", " + to_string(j);//加入数组 } } cout << arr[i] << " " << count << " [" << string1 << "] " << endl; } } } int main() { int array[] = {4, 5, 6, 4, 7, 8, 9, 4, 6}; int n = sizeof(array)/sizeof(array[0]); findcount(array, n); return 0; } 把这个代码加上字符串类型
时间: 2025-03-20 17:12:04 浏览: 51
下面是将原代码扩展到支持整数和字符串类型的版本。为了实现这一点,我们可以利用模板函数来让 `findcount` 支持多种数据类型。
以下是修改后的完整代码:
```cpp
#include <iostream>
#include <vector>
#include <string>
using namespace std;
template<typename T> // 使用模板支持不同类型
void findcount(T arr[], int size) {
bool visited[size];
for (int i = 0; i < size; ++i)
visited[i] = false; // 初始化标记数组
cout << "元素\t出现次数\t下标位置" << endl;
for (int i = 0; i < size; ++i) {
if (!visited[i]) { // 如果当前元素还未被访问过
int count = 1;
string indices = to_string(i); // 转化为文本格式存储索引
visited[i] = true; // 标记已处理过的元素
for (int j = i + 1; j < size; ++j) {
if (arr[j] == arr[i]) { // 找到相同的元素
visited[j] = true;
count++; // 计数加一
indices += ", " + to_string(j); // 存储其索引
}
}
cout << arr[i] << "\t" << count << "\t[" << indices << "]" << endl;
}
}
}
int main() {
// 测试整型数组
int array_int[] = {4, 5, 6, 4, 7, 8, 9, 4, 6};
int n_int = sizeof(array_int)/sizeof(array_int[0]);
cout << "整型数组统计结果:" << endl;
findcount(array_int, n_int);
// 测试字符串数组
string array_str[] = {"apple", "banana", "cherry", "apple", "date", "banana"};
int n_str = sizeof(array_str)/sizeof(array_str[0]); // 注意这里计算的是字节数而非元素个数,需要修正
n_str = 6; // 直接指定正确的长度
cout << "\n字符串数组统计结果:" << endl;
findcount(array_str, n_str);
return 0;
}
```
### 修改说明
通过引入 C++ 的 **模板** 功能 (`template`) ,使得该程序可以接受任意数据类型作为输入参数。这包括但不限于整型、浮点型及字符串等复杂的数据结构。对于字符串数组来说,在主函数部分进行了特别示例演示,并直接设定了数组大小以保证正确运行。
阅读全文
相关推荐














