将未知大小的std ::数组传递给函数 [英] Passing a std::array of unknown size to a function

查看:440
本文介绍了将未知大小的std ::数组传递给函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++ 11中,我将如何编写一个函数(或方法),该函数采用已知类型但未知大小的std ::数组?

In C++11, how would I go about writing a function (or method) that takes a std::array of known type but unknown size?

// made up example
void mulArray(std::array<int, ?>& arr, const int multiplier) {
    for(auto& e : arr) {
        e *= multiplier;
    }
}

// lets imagine these being full of numbers
std::array<int, 17> arr1;
std::array<int, 6>  arr2;
std::array<int, 95> arr3;

mulArray(arr1, 3);
mulArray(arr2, 5);
mulArray(arr3, 2);

在我的搜索过程中,我只找到使用模板的建议,但是那些看起来很乱(标题中的方法定义)

During my search I only found suggestions to use templates, but those seems messy (method definitions in header) and excessive for what I'm trying to accomplish.

有没有简单的方法来使这个工作,就像一个简单的C风格的数组?

Is there a simple way to make this work, as one would with plain C-style arrays?

推荐答案


有没有简单的方法来使这个工作,就像一个简单的C风格的数组? p>

Is there a simple way to make this work, as one would with plain C-style arrays?

否。你真的不能这样做,除非你使你的函数模板(或使用另一种类型的容器,如 std :: vector

No. You really cannot do that unless you make your function a function template (or use another sort of container, like an std::vector, as suggested in the comments to the question):

template<std::size_t SIZE>
void mulArray(std::array<int, SIZE>& arr, const int multiplier) {
    for(auto& e : arr) {
        e *= multiplier;
    }
}

这里是live示例

这篇关于将未知大小的std ::数组传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆