如何改变函数传递变量?

时间:2019-10-07 22:46:34

标签: c++ templates c++17

我使用基准测试了c ++ 17中的算法,以查看它们在不同执行中的速度。

我正在尝试将变量int n1,n2传递给函数,但我不知道该怎么做。

我没有太多使用模板的经验

   using namespace std;

    template <typename TFunc> void RunAndMeasure(const char* title, TFunc func)
      {
       const auto start = chrono::steady_clock::now();
       func();
       const auto end = chrono::steady_clock::now();
       cout << title << ": " << chrono::duration <double, milli>(end - start).count() << " ms" << "\n \n";
      }

  int main()
   {
      int n1 = 3;
      int n2 = 5;
      vector<int> v{0, 1, 2, 3, 4};

      RunAndMeasure("std::warm up", [&v] {

    auto result1 = find(execution::par, begin(v), end(v), n1);
    auto result2 = find(execution::par, begin(v), end(v), n2);

    if (result1 != end(v)) {
    cout << "v contains: " << n1 << '\n';
    } else {
    cout << "v does not contain: " << n1 << '\n';
    }

    if (result2 != end(v)) {
    cout << "v contains: " << n2 << '\n';
    } else {
    cout << "v does not contain: " << n2 << '\n';
    }
});
   return 0;

   }

1 个答案:

答案 0 :(得分:0)

#include <vector>
#include <iostream>
using namespace std;

template <typename TFunc>
void RunAndMeasure(const char *title, TFunc func)
{
    cout << title;
    func();
}

int main()
{
    int n1 = 3;
    int n2 = 5;
    vector<int> v{0, 1, 2, 3, 4};

    RunAndMeasure("some title", [&v, n1, n2] {
        cout << v.size() << n1 << n2;
    });

    return 0;
}