FizzBuzz.cpp with lambdas?

I am trying to write FizzBuzz in C ++ 11 using lambdas, but I am getting a strange compiler error.

the code:

#include <iostream>
#include <string>
#include <sstream>
#include <list>
#include <algorithm>
using namespace std;

string fizzy(int n) {
  int a = n % 3, b = n % 5;

  if (a == 0 && b == 0) {
    return "FizzBuzz";
  }
  else if (a == 0) {
    return "Fizz";
  }
  else if (b == 0) {
    return "Buzz";
  }
  else {
    stringstream out;
    out << n;
    return out.str();
  }
}

void fizzbuzz() {
  string strings[100];
  list<int> range(0, 100);

  for_each(range.begin(), range.end(), [=](int i) {
      strings[i] = fizzy(i);
    });

  for_each(range.begin(), range.end(), [=](int i) {
      cout << strings[i] << endl;
    });
}

int main() { fizzbuzz(); }

Trace:

$ make
g++ -std=c++0x -o fizzy fizzy.cpp
fizzy.cpp: In lambda function:
fizzy.cpp:32:27: error: passing 'const std::string' as 'this' argument of 'std::basic_string<_CharT,
 _Traits, _Alloc>& std::basic_string<_CharT, _Traits, _Alloc>::operator=(std::basic_string<_CharT, _
Traits, _Alloc>&&) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<ch
ar>, std::basic_string<_CharT, _Traits, _Alloc> = std::basic_string<char>]' discards qualifiers
make: *** [fizzy] Error 1
+5
source share
2 answers

You should capture by reference instead of capturing by value in your lambda:

for_each(range.begin(), range.end(), [&](int i) {
//                                    ^
    strings[i] = fizzy(i);
    });

It also helps to solve the problem - by default, the call operator of the generated lambda closure is marked as const.


Note:

Another way to make this compiler is to use a keyword mutable, as in the snippet below:

for_each(range.begin(), range.end(), [=](int i) mutable {
//                                              ^^^^^^^
    strings[i] = fizzy(i);
    });

The keyword mutablediscards constthe generated lambda closure in the call statement.

, , : , , ?

.


UPDATE:

, :

list<int> range(0, 100);

, ( ) 100. , , . (std::iota , ++ 11, ):

#include <algorithm>

list<int> range(100); // Creates a list of 100 elements
iota(begin(range), end(range), 0); // Assigns value 0..99 to those elements
+10

, :

for_each(range.begin(), range.end(), [&strings](int i) {
  strings[i] = fizzy(i);
});

, range, , , , zero:

list<int> range(0, 100);
+1

All Articles