我有一个二维vector< vector<int> >,比如说
contests = [[5, 1], [2, 1], [1, 1], [8, 1], [10, 0], [5, 0]]
我想用accumulate获取第一个元素的总和,因此我使用 lambda 函数来访问向量向量中的正确维度:
#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} \nRun Code Online (Sandbox Code Playgroud)\n … 让我们想象一下我的程序需要用户在不同时间输入。我希望这个输入可以防止刷新cout缓冲区。我可以在不同的流缓冲区上设置cin和吗?cout
相关示例:一个程序读取一行中的两个数字 , n1 n2,并且取决于第一个数字是0, 1, 或2:
n1 = 0:将第二个数字写入n2向量vn1 = 1:输出v[n2]在coutn1 = 2:pop_back()在vMWE 为:
#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) 我知道这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)