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

如何在C++中高效不使用容器找出5个起始索引为1的值的最大索引

Better Ways to Find the 1-Based Index of the Maximum Value

Great question! Your current code works for exactly 5 inputs, but it’s not very scalable (imagine adapting it for 100 values!) and can be made more readable, flexible, and idiomatic. Let’s walk through several improved approaches:

1. Use a Fixed Array (Simple & Scalable for Fixed Input Sizes)

Storing your values in an array lets you loop through them systematically, which is way cleaner than writing separate if statements for each variable.

#include <iostream>
using namespace std;

int main() {
    int nums[5];
    // Read all 5 values into the array
    for (int i = 0; i < 5; ++i) {
        cin >> nums[i];
    }
    
    int max_index = 0; // Track 0-based index of the current maximum
    for (int i = 1; i < 5; ++i) {
        if (nums[i] > nums[max_index]) {
            max_index = i;
        }
    }
    
    cout << max_index + 1 << endl; // Convert to 1-based index
    return 0;
}

Why this is better:

  • Scalable: If you need to handle more than 5 values, just change the array size and loop bounds—no need to add new variables or if checks.
  • Readable: The logic is explicit: we’re tracking the index of the largest value, not overwriting a variable and incrementing a counter (which can be confusing to others reading your code).
  • Consistent: Like your original code, this returns the index of the first occurrence of the maximum value if there are duplicates.

2. Use a Vector (Modern C++ for Flexible Input Sizes)

If you want even more flexibility (like handling a variable number of inputs later), use a vector from the C++ Standard Library instead of a fixed array.

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> nums(5); // Initialize a vector of 5 integers
    for (int i = 0; i < nums.size(); ++i) {
        cin >> nums[i];
    }
    
    int max_idx = 0;
    for (size_t i = 1; i < nums.size(); ++i) {
        if (nums[i] > nums[max_idx]) {
            max_idx = i;
        }
    }
    
    cout << max_idx + 1 << endl;
    return 0;
}

Why this is better:

  • Dynamic size: You can easily adjust the vector’s size at runtime (e.g., read input until the user stops typing) without changing the core logic.
  • Safer: Vectors handle memory management automatically, so you don’t have to worry about buffer overflows like with fixed arrays.

3. Use Standard Library Algorithms (Concise & Idiomatic)

For the most concise and idiomatic C++ solution, use the max_element function from the <algorithm> header. It finds the iterator to the maximum element, and you can compute the index from that.

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> nums(5);
    for (int i = 0; i < 5; ++i) {
        cin >> nums[i];
    }
    
    // Get an iterator pointing to the maximum element
    auto max_it = max_element(nums.begin(), nums.end());
    // Calculate 1-based index: distance from start to max element + 1
    int max_idx = max_it - nums.begin() + 1;
    
    cout << max_idx << endl;
    return 0;
}

Why this is better:

  • Concise: No need to write your own loop to find the maximum—let the standard library do the work for you.
  • Optimized: The standard library algorithms are implemented efficiently, so you get great performance without extra effort.

Note on Edge Cases:

All these approaches return the index of the first occurrence of the maximum value (matching your original code). If you ever need the last occurrence instead, just change the condition from nums[i] > nums[max_index] to nums[i] >= nums[max_index].

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:38:38