You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中查找数组中多个最小值的索引

C++实现查找数组中所有最小值的索引并存储

原代码存在的问题

  • int arr[n]是C风格变长数组,C++标准不支持,运行时可能出现未定义行为
  • MIN = arr[0]在数组未输入元素前就初始化,会读取内存中的垃圾值
  • how_many未初始化,直接操作会导致未定义行为
  • 笔误:tab[i]应为arr[i],且how_many=+1是赋值为1,正确写法是how_many += 1
  • 缺少收集最小值索引、输出结果的核心逻辑

推荐实现(使用vector,无需手动管理内存)

#include <iostream>
#include <vector>

using namespace std;

int main() {
    int n;
    cout << "How many elements should be in the array?" << endl;
    cin >> n;

    vector<int> arr(n);
    for (int i = 0; i < n; ++i) {
        cin >> arr[i];
    }

    // 1. 找出数组中的最小值
    int min_val = arr[0];
    for (int num : arr) {
        if (num < min_val) {
            min_val = num;
        }
    }

    // 2. 统计最小值出现的次数
    int count = 0;
    for (int num : arr) {
        if (num == min_val) {
            ++count;
        }
    }

    // 3. 收集所有最小值的索引
    vector<int> min_indices(count);
    int idx = 0;
    for (int i = 0; i < n; ++i) {
        if (arr[i] == min_val) {
            min_indices[idx++] = i;
        }
    }

    // 输出结果
    cout << "最小值的索引:";
    for (int index : min_indices) {
        cout << index << " ";
    }
    cout << endl;

    cout << "目标数组:arr_min_index[" << count << "] = {";
    for (int i = 0; i < count; ++i) {
        if (i > 0) cout << ", ";
        cout << min_indices[i];
    }
    cout << "}" << endl;

    return 0;
}

兼容C++98的动态数组版本

如果需要兼容旧标准,可使用动态分配内存:

#include <iostream>

using namespace std;

int main() {
    int n;
    cout << "How many elements should be in the array?" << endl;
    cin >> n;

    int* arr = new int[n];
    for (int i = 0; i < n; ++i) {
        cin >> arr[i];
    }

    // 1. 找最小值
    int min_val = arr[0];
    for (int i = 0; i < n; ++i) {
        if (arr[i] < min_val) {
            min_val = arr[i];
        }
    }

    // 2. 统计数量
    int count = 0;
    for (int i = 0; i < n; ++i) {
        if (arr[i] == min_val) {
            ++count;
        }
    }

    // 3. 收集索引
    int* min_indices = new int[count];
    int idx = 0;
    for (int i = 0; i < n; ++i) {
        if (arr[i] == min_val) {
            min_indices[idx++] = i;
        }
    }

    // 输出结果
    cout << "最小值的索引:";
    for (int i = 0; i < count; ++i) {
        cout << min_indices[i] << " ";
    }
    cout << endl;

    cout << "目标数组:arr_min_index[" << count << "] = {";
    for (int i = 0; i < count; ++i) {
        if (i > 0) cout << ", ";
        cout << min_indices[i];
    }
    cout << "}" << endl;

    // 释放内存,避免泄漏
    delete[] arr;
    delete[] min_indices;

    return 0;
}

运行示例

输入:

11
1 2 3 4 1 5 6 7 8 1 9

输出:

最小值的索引:0 4 9 
目标数组:arr_min_index[3] = {0, 4, 9}

内容的提问来源于stack exchange,提问作者jano

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 02:35:27