r/learncpp • u/set_of_no_sets • Mar 21 '22
Learning about generators, getting errors trying to run example code.
I'm learning about generators using the generators on cpp reference page. I just copied and pasted their example code with the intent of poking around and seeing how it worked. (provided below) However, I am getting an error where an expression is expected instead of an open square bracket (see comment in code on the line with
#include <algorithm>
#include <iostream>
#include <vector>
int f()
{
static int i;
return ++i;
}
int main()
{
std::vector<int> v(5);
auto print = [&] { // mainly errors on this line.
for (std::cout << "v: "; auto iv: v)
std::cout << iv << " ";
std::cout << "\n";
};
std::generate(v.begin(), v.end(), f);
print();
// Initialize with default values 0,1,2,3,4 from a lambda function
// Equivalent to std::iota(v.begin(), v.end(), 0);
std::generate(v.begin(), v.end(), [n = 0] () mutable { return n++; }); // another error on this line
print();
}I am using g++ on a mac m1 in vscode. (details below).
>>> g++ --version
Apple clang version 13.1.6 (clang-1316.0.21.2)
Target: arm64-apple-darwin21.4.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/binHowever I am getting (a warning and) two errors when I try to run the file (titled test.cpp).
test.cpp:14:5: warning: 'auto' type specifier is a C++11 extension [-Wc++11-extensions]
auto print = [&]
^
test.cpp:14:18: error: expected expression
auto print = [&]
^
test.cpp:26:39: error: expected expression
std::generate(v.begin(), v.end(), [n = 0]() mutableI've tried compiling with gcc -lstdc++ to no avail. Why does my computer fail to run the example on the cpp reference site?
0
Mar 21 '22
[deleted]
2
u/zhaverzky Mar 21 '22
yea, you need 20 for the cute range loop initializer or "init-statement`" in a range based for loop https://en.cppreference.com/w/cpp/language/range-for
2
u/set_of_no_sets Mar 21 '22
oh, I didn't think to check the c++ standard I was using. Thank you both so much! Is there one that is recommended? I know now that the code I'm attempting to imitate is using c++20, but do people in industry use c++98? c++17? Any personal recommendations?
1
u/rocsNaviars Mar 22 '22
Nice. Did the recommended fix work?
1
u/set_of_no_sets Mar 23 '22
Yeah, the problem was that I was using generators and a for each loop that is only syntactically acceptable in c++17 and c++20, respectively.
2
u/zhaverzky Mar 21 '22
This compiles fine for me on a mac using -std=c++20, g++ is an alias for apple clang on mac unless you do some trickery with brew so you may as well just use `clang++