简体   繁体   中英

'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?

There is nothing wrong with your code. The issue is that libstdc++ does not support std::for_each_n as of yet. If we look at header that defines std::for_each 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM