I have small piece of code for std::for_each_n
loop. I tried running it on inbuilt Coliru compiler GCC C++17 using following command :
g++ -std=c++1z -O2 -Wall -pedantic -pthread main.cpp && ./a.out
But compiler give an error that " 'for_each_n' is not a member of 'std' ".
My code is bellow which is copied from cppreference.
#include <algorithm>
#include <iostream>
#include <vector>
int main()
{
std::vector<int> ns{1, 2, 3, 4, 5};
for (auto n: ns) std::cout << n << ", ";
std::cout << '\n';
std::for_each_n(ns.begin(), 3, [](auto& n){ n *= 2; });
for (auto n: ns) std::cout << n << ", ";
std::cout << '\n';
}
So, Why I'm getting an error?
There is nothing wrong with your code. The issue is that libstdc++ does not support std::for_each_n
until GCC 8 and Clang 8. If we look at the header that defines std::for_each_n
, we see it does not exist.
However, if you have access to libc++, their header from the official mirror does implement std::for_each_n
.
(Update: the current version of the GCC repository now also does include for_each_n
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With