使用 std:array 作为函数的参数

use std:array as an argument of function

本文关键字:函数 参数 std array 使用      更新时间:2023-10-16

我在这里看到过:http://www.cplusplus.com/doc/tutorial/arrays/那 int[N] 与 C++ 中的std::array<int,N>相同。 我想使用这种表示法以避免将 N 作为函数的参数传递。

我想做这样的事情

returnedType function(array tab)

而不是

returnedType function(int tab, int N)

但是我不能制作类型数组,因为我必须写array<int,N>并且我事先不知道 N。 有人有解决方案吗?

function设为函数template,如下所示:

template <size_t N>
void function(std::array<int, N> arr)
{
// do something with arr
}

并像这样称呼它:

int main()
{
std::array<int, 3> a;
function(a);
std::array<int, 15> b;
function(b);
}

如果你事先不知道大小,std::vector 就是你想要的

//function taking vector:
int MyFunc(const std::vector<int>& vec)
{
//.. do stuff
return 5;
}

std::vector<int> myvec;
//add somme entries:
myvec.push_back(1);
myvec.push_back(2);
myvec.push_back(3);
//call function:
int res = MyFunc(myvec);