[英]How to use C++0x lambdas local variables for std::fill()?
因此,我試圖測試一個 lambda 訪問 scope 中的局部變量,大致基於 Bjarne 在 C++0x FAQS 頁面上的一個簡單示例: Z80791B3AE7002CB88C2468.7002CB88C24627www://6ZFA. ~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()>]'
我假設這個 errmsg 表明 std::fill() 簽名需要一個 const Type& 來用於新的值元素分配。
但是,如果我能夠為此目的使用 fill(),如 Bjarne 的示例所示,我不需要在 lambda 捕獲子句中使用引用“[&count]”來重新分配原始通過'return ++count;'索引元素值和遞增計數var lambda 語句塊?
我承認我還不太了解這些 lambda::)
Bjarne 的示例無法編譯。 它無法編譯,除非他們在 C++0x 中以不同方式定義了std::fill
。 也許它來自std::fill
的概念版本,它可以采用 function,但它的實際版本(根據 N3242 的第 25.1 節)采用object ,而不是 ZC1C4245074E17A984D 它將 object 復制到列表的每個元素中。 這就是那個人正在嘗試做的事情。
您正在尋找的 function 是std::generate
。
嘗試這個:
for_each(indices.begin(), indices.end(), [&count](int& it)
{
it = ++count;
});
it
目前是向量的迭代內容,並且是通過引用來的。
我希望添加一個“更新”樣式的答案是可以的,以使未來可能有同樣問題的讀者受益。 請讓我知道,因為我是新來的。
所以,這是我想要做的代碼的最終修改形式:
#include <iostream>
#include <vector>
#include <algorithm>
//Overwrite a vector<int> with incrementing values, base-n.
void init_integers(std::vector<int>& ints, int base) {
int index{ base };
std::generate(ints.begin(), ints.end(), [&index]() {
return index++; //post-incr.
});
}
//Default wrapper to overwrite a vector<int>
// with incrementing values, base-0.
void init_integers(std::vector<int>& ints) {
init_integers(ints, 0);
}
//Test lambda-based vector<int> initialization.
int main() {
std::vector<int> indices( 50 );
init_integers(indices);
//test output loaded indices.
for (auto x : indices) {
std::cout << x << std::endl;
}
}
感謝您提供有用的答案,我發現這是一種更簡單的方法。 從現在開始,我很可能將 lambdas 用於采用 function 對象的算法!
更新 2:
基於 ildjarn 對上述原始帖子的評論:“請注意,這里的確切功能是由新的 C++0x 算法——std::iota 實現的。”
經過測試,我將相應的代碼修改為:
...
#include <numeric>
//Overwrite a vector<int> with incrementing values, base-n.
void init_integers(std::vector<int>& ints, int base) {
std::iota(ints.begin(), ints.end(), base);
}
...
它工作正常。 (“Iota”,s26.7.6,N3242)。
越簡單和干凈(雖然有點晦澀),越容易閱讀——更重要的是——維護。
感謝 ildjarn:(雖然通過這個過程對 go 個人來說是一個很好的練習,以進一步了解 C++0x lambdas!):) -Bud Alverson
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.