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

如何在C++中实现返回两个数组的函数,适配CLRS钢条切割伪代码

问题解答

核心错误原因

C++ 原生数组不支持直接拷贝、赋值,也无法作为函数返回值直接返回。你尝试的多返回值写法属于 C++17 引入的结构化绑定特性,仅支持返回元组、结构体、STL 容器等可解构类型,原生数组不符合要求。

推荐实现方案

方案1:C++17 结构化绑定 + STL容器(最贴近伪代码写法)

用 std::vector 替代原生数组存储结果,返回 std::pair 包装两个vector,调用时直接用结构化绑定接收:

函数实现示例

#include <vector>
#include <climits>
#include <utility>

std::pair<std::vector<int>, std::vector<int>> extended_bottom_up_cut_rod(const std::vector<int>& p, int n) {
    std::vector<int> r(n + 1, 0); // r[i]存储长度为i的钢条最大收益
    std::vector<int> s(n + 1, 0); // s[i]存储长度为i的钢条最优切割的第一段长度

    for (int j = 1; j <= n; ++j) {
        int q = INT_MIN;
        for (int i = 1; i <= j; ++i) {
            if (q < p[i - 1] + r[j - i]) {
                q = p[i - 1] + r[j - i];
                s[j] = i;
            }
        }
        r[j] = q;
    }
    return {r, s};
}

调用示例

// 编译需要开启C++17及以上标准
std::vector<int> p = {1, 5, 8, 9, 10, 17, 17, 20}; // 不同长度钢条的价格表
int n = 8;
auto [r, s] = extended_bottom_up_cut_rod(p, n);

方案2:传引用参数(兼容低版本C++标准)

如果无法使用C++17,将两个结果容器作为引用参数传入函数,不需要返回值:

#include <vector>
#include <climits>

void extended_bottom_up_cut_rod(const std::vector<int>& p, int n, std::vector<int>& r, std::vector<int>& s) {
    r.resize(n + 1, 0);
    s.resize(n + 1, 0);
    // 算法逻辑和上面完全一致
    for (int j = 1; j <= n; ++j) {
        int q = INT_MIN;
        for (int i = 1; i <= j; ++i) {
            if (q < p[i - 1] + r[j - i]) {
                q = p[i - 1] + r[j - i];
                s[j] = i;
            }
        }
        r[j] = q;
    }
}

调用示例

std::vector<int> p = {1, 5, 8, 9, 10, 17, 17, 20};
int n = 8;
std::vector<int> r, s;
extended_bottom_up_cut_rod(p, n, r, s);

关于原生数组的说明

不推荐使用原生数组实现该需求,原生数组要么需要手动管理动态内存容易泄漏,要么需要封装到结构体中徒增代码量,使用std::vector完全可以满足需求,性能和原生数组基本一致,还自带内存管理。
编译时如果遇到结构化绑定报错,记得在编译参数中指定C++17及以上标准,比如GCC/Clang添加-std=c++17编译选项,MSVC添加/std:c++17编译选项。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 01:15:04