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

如何搜索数组元素?实现指定数组的元素查找与位置统计需求

Hey there! Let's tweak your code to perfectly match what you're aiming for. First, let's fix the array to match your specified myarray, clean up the output formatting (no extra trailing comma!), and make the code a bit more flexible. Here's the polished solution:

Array Search Implementation (Matching Your Requirements)
#include <iostream>
#include <vector>
using namespace std;

int main() {
    // Use your exact target array
    int myarray[] = {6,5,2,6,7,8,6};
    // Calculate array length dynamically (no hardcoding 7!)
    int arrLength = sizeof(myarray) / sizeof(myarray[0]);
    
    int target;
    cout << "What number do you want to search : ";
    cin >> target;
    
    int matchCount = 0;
    vector<int> matchIndices; // Store positions where the target is found
    
    // Single loop to count matches AND collect indices (more efficient)
    for(int i = 0; i < arrLength; i++){
        if(myarray[i] == target){
            matchCount++;
            matchIndices.push_back(i);
        }
    }
    
    if(matchCount > 0){
        cout << "your number is found " << matchCount << " times at ";
        // Print indices without a trailing comma
        for(int i = 0; i < matchIndices.size(); i++){
            if(i != 0) cout << ","; // Add comma only before non-first indices
            cout << matchIndices[i];
        }
        cout << endl;
    } else {
        cout << "not found" << endl;
    }
    
    return 0;
}

Key Improvements & Fixes:

  • Swapped to your target array: Replaced the sample x[] with your specified myarray[] = {6,5,2,6,7,8,6}.
  • Dynamic array length: Used sizeof(myarray)/sizeof(myarray[0]) to auto-calculate the array length—this means if you modify the array later, you don't have to manually update the loop limit.
  • Single-pass efficiency: Instead of looping through the array twice (once to count, once to print indices), we collect all matching positions in one loop.
  • Clean output formatting: Eliminated the trailing comma that your original code would have added, so the output looks exactly like your number is found 3 times at 0,3,6 when searching for 6.
  • Simplified logic: Replaced the flag variable with a direct check on matchCount, making the code more readable.

Test Cases:

  • Input 6: Outputs your number is found 3 times at 0,3,6
  • Input 3 (or any non-present number): Outputs not found

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:03:53