小编Gio*_*gre的帖子

C++:在 <numeric> 的累积方法中使用 Lambda 函数

我有一个二维vector< vector<int> >,比如说

\n

contests = [[5, 1], [2, 1], [1, 1], [8, 1], [10, 0], [5, 0]]

\n

我想用accumulate获取第一个元素的总和,因此我使用 lambda 函数来访问向量向量中的正确维度:

\n
#include <iostream>\n#include <vector>\n#include <numeric>\n\nint main() {\n    std::vector< std::vector<int> > \n        contests = {{5, 1}, {2, 1}, {1, 1}, {8, 1}, {10, 0}, {5, 0}};\n    int sum = std::accumulate(contests.begin(),contests.end(), 0, \n                  [](const std::vector<int>& a, const std::vector<int>& b)->int \n                      {return a[0] + b[0];}\n              );\n    \n    std::cout << sum << std::endl;\n    \n    return 0;\n} \n
Run Code Online (Sandbox Code Playgroud)\n …

c++ lambda c++11

1
推荐指数
1
解决办法
275
查看次数

如何防止`std::cin`或`\n`刷新`std::cout`的缓冲区?

让我们想象一下我的程序需要用户在不同时间输入。我希望这个输入可以防止刷新cout缓冲区。我可以在不同的流缓冲区上设置cin和吗?cout

相关示例:一个程序读取一行中的两个数字 , n1 n2,并且取决于第一个数字是0, 1, 或2

  • n1 = 0:将第二个数字写入n2向量v
  • n1 = 1:输出v[n2]cout
  • n1 = 2pop_back()v

MWE 为:

#include <iostream>
#include <vector>

using namespace std;

int main() {
    int size, n1, n2;
    vector<int> v;
    cin >> size;

    while(size--){
        cin >> n1;

        if (n1 == 0)
        {
            cin >> n2;
            v.push_back(n2);
        }
        else if (n1 == 1)
        { …
Run Code Online (Sandbox Code Playgroud)

c++ io iostream streambuf

0
推荐指数
1
解决办法
551
查看次数

与使用模板函数相比,使用“function”对象的代码的执行速度

我知道这std::function是用类型擦除惯用法实现的。类型擦除是一种方便的技术,但它的缺点是它需要在堆上存储底层对象的寄存器(某种数组)。

因此,当创建或复制function对象时,需要进行分配,因此该过程应该比简单地将函数作为模板类型进行操作要慢。

为了检查这个假设,我运行了一个测试函数,该函数累积n = cycles连续的整数,然后将总和除以增量数n。首先编码为模板:

#include <iostream>
#include <functional>
#include <chrono>
using std::cout;
using std::function;
using std::chrono::system_clock;
using std::chrono::duration_cast;
using std::chrono::milliseconds;

double computeMean(const double start, const int cycles) {
    double tmp(start);
    for (int i = 0; i < cycles; ++i) {
        tmp += i;
    }
    return tmp / cycles;
}

template<class T>
double operate(const double a, const int b, T myFunc) {
    return myFunc(a, b);
}
Run Code Online (Sandbox Code Playgroud)

main.cpp

int …
Run Code Online (Sandbox Code Playgroud)

c++ templates functional-programming function-object c++11

0
推荐指数
1
解决办法
81
查看次数