Home > Software engineering >  std::views has not been declared
std::views has not been declared

Time:12-19

I am trying to use the ranges library from c 20 and I have this simple loop.

for (const int& num : vec | std::views::drop(2)) {
    std::cout << num << ' ';
}

I get an error message saying error: 'std::views' has not been declared. I don't get any errors about including the header.

This is my g

g  .exe (MinGW-W64 x86_64-ucrt-posix-seh, built by Brecht Sanders) 11.2.0
Copyright (C) 2021 Free Software Foundation, Inc.

As far as I know it should work as long as you have c 20.

The following example does not compile on my machine:

#include <iostream>
#include <ranges>
#include <vector>

int main() {
    std::cout << "Hello world!";
    std::vector <int> vec = {1, 2, 3, 4, 5};
    // print entire vector
    for (const int& num : vec) {
        std::cout << num << ' ';
    }
    std::cout << "\n";
    // print the vector but skip first few elements
    for (const int& num : vec | std::views::drop(2)) {
        std::cout << num << ' ';
    }
    return 0;
}

CodePudding user response:

Depending on the version of your compiler, different standards are the default. For 11.2 it is C 17 AFAIK.
Cou can just add a flag and it compiles:

g --std=c 20 main.cc

  • Related