酷代码 AI
菜单
服务商

不使用vector和algorithm找出n个数字中前3个最小值的C++实现

```cpp #include <iostream> using namespace std; // 交换两个数的值 void swap(int &a, int &b) { int temp = a; a = b; b = temp; } // 找出前3个最小的值 void findThreeSmallest(int arr[], int n) { if (n < 1) return; int first = arr[0], second = 1e9, third = 1e9; for (int i = 1; i < n; i++) { if (arr[i] < first) { third = second; second = first; first = arr[i]; } else if (arr[i] < second) { third = second; second = arr[i]; } else if (arr[i] < third) { third = arr[i]; } } cout << "前3个最小的值为: "; if (n >= 1) cout << first << " "; if (n >= 2) cout << second << " "; if (n >= 3) cout << third << " "; cout << endl; } int main() { int n; cout << "请输入数字的数量 n: "; cin >> n; int *arr = new int[n]; cout << "请输入 " << n << " 个数字: "; for (int i = 0; i < n; i++) { cin >> arr[i]; } findThreeSmallest(arr, n); delete[] arr; return 0; } ``` ### 代码解释 1. **`swap` 函数**:用于交换两个整数的值,通过引用传递参数,实现两个数的交换。 2. **`findThreeSmallest` 函数**: - 首先初始化 `first` 为数组的第一个元素,`second` 和 `third` 初始化为一个较大的值(这里用 `1e9` 表示)。 - 遍历数组,根据当前元素与 `first`、`second`、`third` 的大小关系更新这三个值。 - 最后输出前 3 个最小的值。 3. **`main` 函数**: - 提示用户输入数字的数量 `n`。 - 动态分配一个大小为 `n` 的数组。 - 提示用户输入 `n` 个数字并存储到数组中。 - 调用 `findThreeSmallest` 函数找出前 3 个最小的值。 - 释放动态分配的数组内存。 ######[AI问答 | 631点数解答 | 2026-04-04 19:54:30]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]