c++将向量的内容作为参数传递给函数

c++ pass content of a vector as parameters to a function

本文关键字:参数传递 函数 向量 c++      更新时间:2023-10-16

在python中,我们可以做这样的事情:

def test(a, b, c):
    return a+b+c
x = [1, 2, 3]
y = test(*x)

我们能在C++中做一些类似的事情吗?

到目前为止提出的解决方案是基于函数参数的运行时迭代,这会产生一些成本。他们还假设参数类型是相同的。如果在编译时参数的数量是已知的(通常是已知的(,那么不同的解决方案将类似于

template <typename F, typename T>
auto tuple_call3(F&& f, const T& t)
-> decltype(std::forward<F>(f)(std::get<0>(t), std::get<1>(t), std::get<2>(t)))
   { return std::forward<F>(f)(std::get<0>(t), std::get<1>(t), std::get<2>(t)); }
struct test
{
   template <typename A, typename B, typename C>
   auto operator()(const A& a, const B& b, const C& c)
   -> decltype(a + b + c)
      { return a + b + c; }
};
int main()
{
    auto x = std::make_tuple(1, 2, 3);
    auto y = tuple_call3(test(), x);
    cout << y << endl;
}

其没有运行时成本并且与异构参数类型一起工作。我现在没有时间进一步开发它,但要使它完全通用,我们需要

  • 在任何地方使用通用引用(如F&&(和转发(如std::forward<F>(f)(,当然也包括函数参数。

  • 使tuple_call变差。为此,如果L是元组的大小(通过tuple_size(,则我们需要在编译时生成序列0,...,L-1(例如,参见此处的函数range(。如果N...是此序列,则使用std::get<N>(t)...

  • 让它与简单的函数一起工作。现在test是一个函数对象,也可以是lambda,但普通函数不应该是模板,或者显式指定其模板参数(在tuple_call上(;否则不能推导出其类型CCD_ 11。

如果所有这些都集成到C++语言中,那就太好了,但现在还没有。至少有一些工具可以制作出大致相同的东西。顺便说一句,我不知道Python中等效程序的运行时成本是多少。

至少,我认为下面的代码接近您的python代码

int test(const std::vector<int>& v)
{
    return std::accumulate(v.begin(), v.end(), 0);
}
std::vector<int> x = { 1, 2, 3 };
int y = test(x); 

可以。例如

#include <numeric>
#include <initializer_list>
int test( std::initializer_list<int> l )
{
    return std::accumulate( l.begin(), l.end(), 0 );
}
int y = test( { 1, 2, 3 } );

int test( const int a[] )
{
    return a[0] + a[1] + a[2];
}
int a[] = { 1, 2, 3 };
int y = test( a );

#include <vector>
#include <numeric>
int test( const std::vector<int> &v )
{
    return std::accumulate( v.begin(), v.end(), 0 );
    // or return v[0] + v[1] + v[2];
}
std::vector<int> v = { 1, 2, 3 };
int y = test( v );

不,没有一个线性函数可以将容器转换为函数所需的参数。这是因为在C++中,函数调用是在编译时处理的,而容器的内容在运行时是已知的。

所以我最接近的例子是

int test(int a, int b, int c) { return a + b + c; }
std::vector<int> x = { 1, 2, 3 };
int y = test(x[0], x[1], x[2]);

请注意,由于在python中必须注意容器中的元素数量与预期参数匹配,因此给定的示例不太可用。

是的,如果您只是在谈论将文字转换为类似向量的对象,请参阅std::initializer_list(C++11(

template <typename T>
void test(std::initializer_list<T> aList) {
    //do stuff with aList, for example std::accumulate,
    //or make a vector with it: std::vector<T> v(aList);
}
auto x = {10, 11, 12};
test(x)

但是,如果你需要使用一个具有"正常"参数的函数,你需要使用vaargs,参见vaarg中的示例,所以答案可能是"否"。