将未知大小的 std::array 传递给函数

新手上路,请多包涵

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

 // 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);

在我的搜索过程中,我只发现了使用模板的建议,但这些建议看起来很混乱(标题中的方法定义)并且对于我想要完成的事情来说太过分了。

有没有一种简单的方法来完成这项工作,就像使用普通的 C 样式数组一样?

原文由 Adrian 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 765
2 个回答

有没有一种简单的方法来完成这项工作,就像使用普通的 C 样式数组一样?

不,除非您将函数设为函数 _模板_(或使用另一种容器,如 std::vector ,如问题评论中所建议的那样),否则您真的不能这样做:

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

这是一个 活生生的例子

原文由 Andy Prowl 发布,翻译遵循 CC BY-SA 3.0 许可协议

当然,在 C++11 中有一种简单的方法可以编写一个函数,该函数采用已知类型但大小未知的 std::array。

如果我们无法将数组大小传递给函数,那么我们可以将数组开始的内存地址与数组结束的第二个地址一起传递。稍后,在函数内部,我们可以使用这 2 个内存地址来计算数组的大小!

 #include <iostream>
#include <array>

// The function that can take a std::array of any size!
void mulArray(int* piStart, int* piLast, int multiplier){

     // Calculate the size of the array (how many values it holds)
     unsigned int uiArraySize = piLast - piStart;

     // print each value held in the array
     for (unsigned int uiCount = 0; uiCount < uiArraySize; uiCount++)
          std::cout << *(piStart + uiCount) * multiplier << std::endl;
}

int main(){

     // initialize an array that can can hold 5 values
     std::array<int, 5> iValues{ 5, 10, 1, 2, 4 };

     // Provide a pointer to both the beginning and end addresses of
     // the array.
     mulArray(iValues.begin(), iValues.end(), 2);

     return 0;
}

控制台输出:

 10, 20, 2, 4, 8

原文由 David M. Helmuth 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题