如何搜索数组元素?实现指定数组的元素查找与位置统计需求
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 specifiedmyarray[] = {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,6when searching for 6. - Simplified logic: Replaced the
flagvariable with a direct check onmatchCount, making the code more readable.
Test Cases:
- Input
6: Outputsyour number is found 3 times at 0,3,6 - Input
3(or any non-present number): Outputsnot found
内容的提问来源于stack exchange,提问作者Natnael
相关产品推荐
相关产品推荐

