Reputation: 1339
I'm trying to get C++11 lambdas down. I'm sure there is a way to initialize temp
with a lambda (granted maybe not the best way), but I've been unable to come up with this solution.
The desired result: temp
should contain an empty string for every element in data
.
Here is the way I would usually initialize temp
:
vector<string> temp;
for(auto i : data){
temp.push_back("");
}
Here is the closest (I believe) that I've come to a lambda solution:
auto num = data.size(); //can't pass class members (data) to capture list
auto temp = [num](vector<string> strs) -> vector<string> {
for(int i = 0; i < num; ++i){
strs.push_back("");
}
return strs;
};
However, when I call temp.size()
, I get the following error:
struct ProteinAnalyzer::convert_sequences()::__lambda0’ has no member named ‘size’
(using GCC 4.8.1)
I even explicitely declared the return type, so I'm puzzled as to why this lambda does not return vector<string>
Upvotes: 2
Views: 179
Reputation: 1339
Thanks to the comments, I have figured out the solution to my problem. Here is how I initialized temp
with a lambda function if anyone is curious:
auto num = data.size();
auto temp = [num](){
vector<string> temp;
for(int i = 0; i < num; ++i){
temp.push_back("");
}
return temp;
}();
My problem was that I was equating the lambda with its return - two separate things.
...Although, as mentioned in the comments, vector<string> temp(data.size(), "");
is probably the best (most succint) way.
Upvotes: 1