gpt4 book ai didi

c++ - 使用 std::bind 将函数传递给函数

转载 作者:行者123 更新时间:2023-11-27 23:02:16 25 4
gpt4 key购买 nike

过去两天我一直在研究这些功能,使用 boost 后我的 CPU 和 Wall times 终于可以工作了,

最后一根刺让我无法回头,我正在尝试将一个带有参数的函数传递给另一个函数,该函数使用 std::bind 返回一个值,

我是一名学生,这对我来说是全新的,边学边学,

int CA1::binarySearch(vector<int> v, int target)
{

int top, bottom, middle;
top = vecSize - 1;
bottom = 0;

while (bottom <= top)
{
middle = (top + bottom) / 2;
if (v[middle] == target)
return middle;
else if (v[middle] > target)
top = middle - 1;
else
bottom = middle + 1;
}
return -1;
}


double CA1::measure(std::function<void()> function) {
auto startCpu = boost::chrono::process_real_cpu_clock::now();
auto startWall = boost::chrono::process_system_cpu_clock::now();

function();

auto durationCpu = boost::chrono::duration_cast<boost::chrono::nanoseconds>
(boost::chrono::process_real_cpu_clock::now() - startCpu);
auto durationWall = boost::chrono::duration_cast<boost::chrono::nanoseconds>
(boost::chrono::process_system_cpu_clock::now() - startWall);


double cpuTime = static_cast<double>(durationCpu.count()) * 0.000001;
double wallTime = static_cast<double>(durationWall.count()) * 0.000001;

/*return static_cast<double>(duration.count()) * 0.000001;*/

cout << "Cpu time " << cpuTime << endl;
cout << "Wall time " << wallTime << endl;

return cpuTime;
}

void CA1::DoTests() {

auto time = measure(std::bind(binarySearch, vectorUnordered, 2));
}

我得到的错误是:

error C3867: 'CA1::binarySearch': function call missing argument list; use '&CA1::binarySearch' to create a pointer to member

但根据我所阅读的内容和其他用户看到的代码片段,我在 DoTests() 中的代码是正确的。

最佳答案

类函数有明确的'this'参数,需要作为第一个参数传入:

measure(std::bind(&CA1::binarySearch, this, vectorUnordered, 2))

关于c++ - 使用 std::bind 将函数传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26535844/

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