std::views 尚未声明

wyv*_*ern 4 c++ c++20 std-ranges

我正在尝试使用rangesc++20 中的库,并且有一个简单的循环。

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

我收到一条错误消息说error: 'std::views' has not been declared. 我没有收到任何关于包含标题的错误。

这是我的g++

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

据我所知,只要你有 c++20,它就应该可以工作。

以下示例无法在我的机器上编译:

#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;
}
Run Code Online (Sandbox Code Playgroud)

Oli*_*zdi 6

根据编译器的版本,默认标准不同。因为11.2它是 C++ 17 AFAIK。
Cou 只需添加一个标志即可编译:

g++ --std=c++20 main.cc