gpt4 book ai didi

C++:如何用单个命令替换复杂的迭代?

转载 作者:搜寻专家 更新时间:2023-10-31 00:07:33 24 4
gpt4 key购买 nike

问题

我有时有复杂的迭代过程,必须在代码中重复多次,但每次迭代执行的表达式在代码的不同位置有所不同。必须在所有地方重写迭代过程是丑陋的并且容易出错。我怎样才能结束这个迭代过程?

示例

例如考虑这个相对复杂的迭代

std::string bitmask(K, 1); // K leading 1's
bitmask.resize(N, 0); // N-K trailing 0's

// print integers and permute bitmask
do {
// Loop through BIG and SMALL indices
for (size_t BIGindex = 0; BIGindex < nbBigs; ++BIGindex)
{
size_t nbSmalls;
if (BIGindex == nbBigs)
{
nbSmalls = nbSmallsOfLastBig;
} else
{
nbSmalls = nbSmallsStandard;
}
for (size_t SMALLindex = 0; SMALLindex < nbSmalls; ++SMALLindex)
{
// doStuff with bitmask, BIGindex and SMALLindex
}
}
} while (std::prev_permutation(bitmask.begin(), bitmask.end()));

我如何定义命令/别名(缺少更好的词),例如“doComplexIteration”,将所有这些迭代包装到一个更简单的命令中。有点像

doComplexIteration
{
// doStuff with bitmask, BIGindex and SMALLindex
}

一个不完全令人满意的解决方案

一种方法是将要完成的事情包装在一个函数中,例如

void doComplexIterationOnFunction(void (*doStuff)(std::string bitmask, size_t BIGindex, size_t SMALLindex))
{
std::string bitmask(K, 1); // K leading 1's
bitmask.resize(N, 0); // N-K trailing 0's

// print integers and permute bitmask
do {
// Loop through BIG and SMALL indices
for (size_t BIGindex = 0; BIGindex < nbBigs; ++BIGindex)
{
size_t nbSmalls;
if (BIGindex == nbBigs)
{
nbSmalls = nbSmallsOfLastBig;
} else
{
nbSmalls = nbSmallsStandard;
}
for (size_t SMALLindex = 0; SMALLindex < nbSmalls; ++SMALLindex)
{
(*doStuff)(bitmask, BIGindex, SMALLindex);
}
}
} while (std::prev_permutation(bitmask.begin(), bitmask.end()));
}

然后称它为

doComplexIterationOnFunction(doSpecificStuff);

然而,它迫使我系统地将我希望在每次迭代中执行的任何代码包装在一个函数中,这有点麻烦而且有点愚蠢,因为有时代码很短。

最佳答案

您可以将函数设为模板类型,而不是使用函数指针,这样您就可以在调用点传递一个 lambda。看起来像

temaplte<typename Function>
void doComplexIterationOnFunction(Function doStuff)
{
std::string bitmask(K, 1); // K leading 1's
bitmask.resize(N, 0); // N-K trailing 0's

// print integers and permute bitmask
do {
// Loop through BIG and SMALL indices
for (size_t BIGindex = 0; BIGindex < nbBigs; ++BIGindex)
{
size_t nbSmalls;
if (BIGindex == nbBigs)
{
nbSmalls = nbSmallsOfLastBig;
} else
{
nbSmalls = nbSmallsStandard;
}
for (size_t SMALLindex = 0; SMALLindex < nbSmalls; ++SMALLindex)
{
std::invoke(doStuff, bitmask, BIGindex, SMALLindex);
}
}
} while (std::prev_permutation(bitmask.begin(), bitmask.end()));
}

然后你会这样调用它

doComplexIterationOnFunction(doSpecificStuffFunction) // pass function
doComplexIterationOnFunction(doSpecificStuffFuntor) // pass functor
doComplexIterationOnFunction([](auto foo, auto bar, auto baz) { return foo + bar - baz; }) // pass lambda

关于C++:如何用单个命令替换复杂的迭代?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52728067/

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