c++ - 如何为 std::fill() 使用 C++0x lambdas 局部变量?

标签 c++ c++11 lambda fill iota

因此,我尝试测试一个访问局部变量的 lambda 在它使用的范围内,大致基于 Bjarne 在 C++0x FAQS 页面上的一个简单示例: http://www2.research.att.com/~bs/C++0xFAQ.html#lambda

当我尝试这个简单的测试代码时:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

//Test std::fill() with C++0x lambda and local var
void f (int v) { 
    vector<int> indices(v);
    int count = 0;
    fill(indices.begin(), indices.end(), [&count]() {
        return ++count;
    });

    //output test indices
    for (auto x : indices) {
        cout << x << endl;
    }
}

int main() {
    f(50);
}

我得到错误:

required from 'void std::fill(_ForwardIterator, _ForwardIterator, const _Tp&) [with _ForwardIterator = __gnu_cxx::__normal_iterator<int*, std::vector<int> >, _Tp = f(int)::<lambda()>]'

我假设此错误消息指示 std::fill() 签名需要 const Type& 以用于新值元素分配。

但是,如果我能够为此目的使用 fill(),如 Bjarne 的示例所示,我是否不需要在 lambda 捕获子句中使用引用“[&count]”来能够通过 'return++count;' 将原始索引元素值重新分配给递增计数 var lambda 语句 block ?

我承认我还不太了解这些 lambda 表达式! :)

最佳答案

Bjarne 的示例无法编译。它无法编译,除非他们在 C++0x 中以不同方式定义了 std::fill。也许它来自 std::fill 的概念化版本,它可以接受一个函数,但它的实际版本(根据 N3242 的第 25.1 节)接受一个对象,不是一个功能。它将那个对象复制到列表的每个元素中。这就是那个人正在尝试做的事情。

您正在寻找的函数是 std::generate

关于c++ - 如何为 std::fill() 使用 C++0x lambdas 局部变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6639700/

相关文章:

c++ - 为什么类的常量数据成员需要在构造函数中初始化?

c++ - D3D11 CreateSwapChainForHwnd 失败,出现 DXGI_ERROR_INVALID_CALL 或 E_INVALIDARG

c++ - 在异常中不嵌入 std::string 的规则是否仍然适用于移动构造函数?

c# - 深入学习 C# 表达式树的最佳资源是什么?

c++ - 何时使用函数模板而不是通用 lambda?

c++ - Cuda 写入设备上的数组不会更改值

c++平均函数无法正常工作

c++ - 在这种情况下,为什么 void 指针的行为与普通整数指针的行为不同?

c++ - 如何消除这个模板的歧义?

c++ - Lamba 类型不是由模板函数或 auto 关键字推导出来的