我正在尝试使用 lambda 在 C++11 中编写 FizzBuzz,但我遇到了一个奇怪的编译器错误。
代码:
#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(); }
痕迹:
$ 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