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

如何基于线性搜索实现查找数组中目标整数的所有出现索引

解决线性搜索返回所有匹配索引的问题

原代码的核心问题是找到第一个匹配项就直接返回,且返回类型仅能存储单个索引。以下是修改后的完整代码,实现输出目标整数所有出现的索引:

// 基于线性搜索查找数组中指定整数的所有出现索引
// Author: Y K

#include <iostream>
#include <vector>  // 引入vector容器存储多个索引
using namespace std;

// 修改函数原型:返回存储索引的vector<int>
vector<int> searchList(int[], int, int); 

const int SIZE = 8;

int main()
{
    int nums[SIZE] = {3, 6, -19, 5, 5, 0, -2, 99};
    vector<int> foundIndices;  // 用vector存储所有匹配的索引
    int ch;

    cout << "Enter a number to search for:" << endl;
    cin >> ch;

    foundIndices = searchList(nums, SIZE, ch);

    if (foundIndices.empty())
        cout << "The number " << ch << " was not found in the list" << endl;
    else
    {
        cout << "The number " << ch << " appears at positions: ";
        for (size_t i = 0; i < foundIndices.size(); ++i)
        {
            // 输出位置(索引+1),和原代码的输出逻辑保持一致
            cout << foundIndices[i] + 1;
            if (i != foundIndices.size() - 1)
                cout << ", ";
        }
        cout << endl;
    }

    return 0;
}

//*******************************************************************
//  searchList
//
//  task:          搜索数组中指定值的所有出现位置
//  data in:       数组、数组元素个数、要查找的值
//  data returned: 存储所有匹配索引的vector,为空则表示未找到
//
//*******************************************************************

vector<int> searchList(int List[], int numElems, int value)
{
    vector<int> indices;
    // 修复原循环的越界问题:count < numElems(索引从0到numElems-1)
    for (int count = 0; count < numElems; count++)
    {
        if (List[count] == value)
            indices.push_back(count);  // 找到匹配项就加入vector,不直接返回
    }

    return indices;  // 返回所有匹配的索引,空vector表示未找到
}

关键修改说明

  • 返回类型调整:将searchList的返回值从单个int改为vector<int>,支持存储多个匹配索引。
  • 循环逻辑修复:原代码count <= numElems会导致数组越界(数组最大索引为numElems-1),修改为count < numElems避免非法内存访问。
  • 匹配项处理:找到匹配值时不再立即返回,而是将索引添加到vector中,继续遍历整个数组收集所有匹配项。
  • 主函数输出逻辑:通过判断vector是否为空处理未找到的情况,若不为空则遍历输出所有匹配位置(保持原代码“位置=索引+1”的逻辑)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 16:40:27