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

C++实现卡普雷卡常数计算报错:Sort匹配失败及vector下标越界

解决卡普雷卡常数C++代码的编译与运行错误

问题分析

原代码存在多个核心错误,导致编译失败和运行时异常:

  • std::sort使用错误:直接对int变量调用std::sort,不符合函数要求(需传入迭代器或数组指针),引发编译错误std::Sort_Unchecked:no matching overloaded function found。
  • vector初始化与输入逻辑错误:全局vector<int> Numbers(size)初始化时size默认值为0,导致display函数的范围for循环无法执行输入;main函数中误将vector元素值作为索引访问Numbers[i],引发vector subscript out of range。
  • 卡普雷卡操作逻辑错误:未将四位数拆分为单个数字排序,且循环中未更新目标数值,会导致无限循环。

修正后的代码

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

void display(vector<int>& numbers) {
    int size;
    cout << "How many try cases do you wanna set up? \n";
    cin >> size;
    cout << "Input\n";
    numbers.reserve(size);
    for (int i = 0; i < size; ++i) {
        int num;
        cin >> num;
        numbers.push_back(num);
    }
}

int sort_and_reform(int num, bool descending) {
    int digits[4];
    digits[0] = num / 1000;
    digits[1] = (num / 100) % 10;
    digits[2] = (num / 10) % 10;
    digits[3] = num % 10;
    
    if (descending) {
        sort(digits, digits + 4, greater<int>());
    } else {
        sort(digits, digits + 4);
    }
    
    return digits[0] * 1000 + digits[1] * 100 + digits[2] * 10 + digits[3];
}

int main() {
    vector<int> numbers;
    display(numbers);
    
    for (int num : numbers) {
        int count = 0;
        int current = num;
        
        if (current < 1000 || current > 9999) {
            cout << "Invalid number: " << current << " (must be a 4-digit number)\n";
            continue;
        }
        
        int d1 = current / 1000, d2 = (current / 100) %10, d3=(current/10)%10, d4=current%10;
        if (d1 == d2 && d2 == d3 && d3 == d4) {
            cout << "Invalid number: " << current << " (all digits are the same)\n";
            continue;
        }
        
        while (current != 6174) {
            int desc = sort_and_reform(current, true);
            int asc = sort_and_reform(current, false);
            current = desc - asc;
            count++;
        }
        cout << count << "\n";
    }
    return 0;
}

关键修改说明

  • 修复std::sort调用:新增sort_and_reform函数,先将四位数拆分为单个数字数组,再对数组执行排序,最后重组为整数,符合std::sort的参数要求。
  • 修正vector输入逻辑:将size改为display局部变量,通过push_back向vector添加输入值;main函数中直接遍历vector元素,避免用元素值作为索引导致越界。
  • 完善操作逻辑:每次循环更新current为排序后的差值,确保循环正常终止;新增输入合法性检查,过滤非四位数和全相同数字的无效输入。
  • 移除冗余全局变量:改用局部变量和函数参数传递数据,避免全局变量初始化顺序问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 19:07:15