Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'for_each_n' is not a member of 'std' in C++17

Tags:

c++

foreach

c++17

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?

like image 898
msc Avatar asked Dec 03 '22 12:12

msc


1 Answers

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)

like image 170
NathanOliver Avatar answered Dec 27 '22 02:12

NathanOliver