''for_each_n' is not a member of 'std' in 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?



Solution 1:[1]

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)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 wovano