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

如何不使用模板实现C++中canConstruct函数的等效版本?

当然可以不用模板实现等效的canConstruct函数,核心原因是原生数组作为函数参数时会退化为指针,丢失大小信息,所以我们需要换一种方式传递数组长度信息,或者改用更易用的容器类型。下面是几种可行方案:

方案1:显式传递数组长度参数

把数组长度作为额外参数传给函数,不用依赖模板推导大小。修改后的代码如下:

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

bool canConstruct(string target, string* wordBank, int arrayLength)
{
    int n = target.size();
    for(int i = 0; i < arrayLength; i++)
    { 
        if(arrayLength < n){return (wordBank[i] == "a");}
    }
    return false;
}

int main() 
{
    string wordbank[6] = {"r","a","t","ge","t","u"};
    bool output = canConstruct("targets", wordbank, sizeof(wordbank)/sizeof(wordbank[0]));
    cout << output << endl;
    return 0;
}

调用时用sizeof(wordbank)/sizeof(wordbank[0])计算数组长度,这是C++中获取原生数组大小的经典方式——注意只能在数组定义的作用域中使用,一旦数组退化为指针就没法用这个方法了。

方案2:改用std::vector代替原生数组

如果可以修改数组类型,用std::vector<string>替代原生数组会更简洁,函数不需要模板,直接通过vector的size()方法获取长度:

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

bool canConstruct(string target, const vector<string>& wordBank)
{
    int m = wordBank.size();
    int n = target.size();
    for(int i = 0; i < m; i++)
    { 
        if(m < n){return (wordBank[i] == "a");}
    }
    return false;
}

int main() 
{
    vector<string> wordbank = {"r","a","t","ge","t","u"};
    bool output = canConstruct("targets", wordbank);
    cout << output << endl;
    return 0;
}

这种方式更符合现代C++编程风格,vector会自动管理内存,也避免了原生数组的诸多限制。

为什么原实现需要模板?

原代码里用模板是因为函数参数是string (&arr)[array_length]——这是固定大小的数组引用,不同大小的数组属于不同类型,必须用模板让编译器推导array_length的值,才能让函数接受任意大小的原生数组引用。如果不用模板,没法直接写出能接受任意大小原生数组引用的函数,因为数组大小是类型的一部分,不能作为变量传递。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 08:23:18