gpt4 book ai didi

c++ - 需要一个 constexpr 来使 for 循环中的值加倍

转载 作者:行者123 更新时间:2023-11-27 22:59:07 30 4
gpt4 key购买 nike

我想在每次处理 for 循环时将一个值加倍。到目前为止,我有以下代码:

    constexpr size_t doubleN(size_t n, size_t iteration)
{
return n * iteration;
};

const array<size_t, 9> iterationArray = { 1, 2, 3, 4, 5, 6, 7, 8, 10 };
for (size_t i = 1; i <= 10; i++)
{
Insertionsort<double, doubleN(INITIAL_SIZE_N_INSERTIONSORT, iterationArray[i])> insertionsort;
Util<doubleN(INITIAL_SIZE_N_INSERTIONSORT, iterationArray[i])> util;
array<double, doubleN(INITIAL_SIZE_N_INSERTIONSORT, iterationArray[i])> arrayRef;
util.generateRandomDoubleArray(arrayRef);
util.overwriteProcessorCache();

cout << "Measure Insertionsort version 1 with n = " << INITIAL_SIZE_N_INSERTIONSORT << "." << endl;
util.startTimeMeasure();
insertionsort.sortVersion1(arrayRef);
util.stopTimeMeasure();
cout << "Measureing Insertionsort version 1 successful." << endl;
}

我的问题是,我不能将 constexpr 返回的值加倍,因为它总是需要一个常量值作为参数。您是否知道如何获得一个始终返回一个基于先前加倍值加倍的值的 constexpr

最佳答案

首先,将你的运行时i参数转换为编译时值:

template <std::size_t I>
void foo()
{
Insertionsort<double, doubleN(INITIAL_SIZE_N_INSERTIONSORT, I)> insertionsort;
Util<doubleN(INITIAL_SIZE_N_INSERTIONSORT, I)> util;
array<double, doubleN(INITIAL_SIZE_N_INSERTIONSORT, I)> arrayRef;
util.generateRandomDoubleArray(arrayRef);
util.overwriteProcessorCache();

cout << "Measure Insertionsort version 1 with n = " << INITIAL_SIZE_N_INSERTIONSORT << "." << endl;
util.startTimeMeasure();
insertionsort.sortVersion1(arrayRef);
util.stopTimeMeasure();
cout << "Measureing Insertionsort version 1 successful." << endl;
}

然后做一个循环:

template <size_t ... Is>
void foos()
{
int dummy[] = {0, (foo<Is>(), 0)...};
(void) dummy; // avoid warning for unused variable
}

或者用 C++17 的折叠表达式:

template <size_t ... Is>
void foos()
{
(foo<Is>(), ...);
}

并称它为:

foos<1, 2, 3, 4, 5, 6, 7, 8, 9, 10>();

关于c++ - 需要一个 constexpr 来使 for 循环中的值加倍,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29458977/

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