gpt4 book ai didi

c++ - 如何分解 vector 并将其值用作函数的参数?

转载 作者:太空狗 更新时间:2023-10-29 21:05:05 25 4
gpt4 key购买 nike

我目前正在做的是:

std::vector<sometype> myparams;
...
while (...)
myparams.push_back(somevalue);
...

somefunction(myparams[0], myparams[1], myparams[2], otherargument);

我有许多接受 1 到 100 个参数的 somefunction 的实现。我无法更改 somefunction 但是我想知道是否有更漂亮的方法来使用它,因此无论 myparams 的大小是什么,都可以通过创建另一个函数/宏来接受 vector 作为参数并使用 vector 的所有值调用 somefunction作为参数。

有什么想法吗?

非常感谢。

最佳答案

好吧,你真的不应该那样做,但是你开始吧:) 使用 boost::preprocessor:

#include "stdafx.h"
#include <vector>

void somefunction(int p1)
{ std::cout << p1 << " " << std::endl;}
void somefunction(int p1, int p2)
{ std::cout << p1 << " " << p2 << std::endl;}
void somefunction(int p1, int p2, int p3)
{ std::cout << p1 << " " << p2 << " " << p3 << std::endl;}
void somefunction(int p1, int p2, int p3, int p4)
{ std::cout << p1 << " " << p2 << " " << p3 << " " << p4 << std::endl;}

#define MAX_ARGS 4

#include <boost/preprocessor/repetition.hpp>

void UnpackVector(const std::vector<int> &v)
{
#define MACRO(z, n, _) \
case n: somefunction(\
BOOST_PP_ENUM_BINARY_PARAMS(BOOST_PP_INC(n), v[,]BOOST_PP_INTERCEPT) \
);break;

switch(v.size() - 1)
{
BOOST_PP_REPEAT(MAX_ARGS, MACRO, nil)
}
}

void Run()
{
int v_[] = { 42, 41, 40, 39 };
std::vector<int> v(v_, v_ + sizeof(v_) / sizeof(int));

UnpackVector(v);
}

只是为了笑。

关于c++ - 如何分解 vector 并将其值用作函数的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10815797/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com