【问题标题】:How to change default version of C++ to check errors and warings in VSCode?如何更改 C++ 的默认版本以检查 VSCode 中的错误和警告?
【发布时间】:2022-01-09 15:39:28
【问题描述】:

我是学习计算机科学的学生,刚开始编程。使用 VSCode 时遇到问题。 这是我的 ma​​in.cpp

#include <bits/stdc++.h>

using namespace std;

template <template <typename, typename> class C, typename K, typename V>
std::ostream &operator<<(std::ostream &os, C<K, V> a)
{
    os << "[ ";
    for (auto t : a)
    {
        os << t << " ";
    }
    os << "]";
    return os;
}
template <template <typename> class V, typename T>
std::ostream &operator<<(std::ostream &os, V<T> a)
{
    os << "[ ";
    for (T t : a)
    {
        os << t << " ";
    }
    os << "]";
    return os;
}
template <typename T, typename V>
std::ostream &operator<<(std::ostream &os, pair<T, V> a)
{
    os << "[" << a.first << ", " << a.second << "]";
    return os;
}

template <typename T>
std::istream &operator>>(std::istream &is, vector<T> &a)
{
    for (T &t : a)
    {
        is >> t;
    }
    return is;
}
template <typename T, typename V>
std::istream &operator>>(std::istream &is, pair<T, V> &a)
{
    is >> a.first >> a.second;
    return is;
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    // freopen("input.txt", "r", stdin);
    // freopen("output.txt", "w", stdout);
    freopen("error.txt", "w", stderr);
    int t = 1;
    // cin >> t;
    while (t--)
    {
        vector<int> a(5);
        map<int, int> b;
        for (int i = 0; i < 5; i++)
        {
            a[i] = i * 2;
            b[i] = i * 2;
        }
        cout << a << endl;
        cout << b << endl;
    }
}

当我编辑 no operator ">>

问题是我已经用命令完美地编译了文件(没有发现错误)

g++ -std=c++20 main.cpp -o main

然后我用这个命令重新编译

g++ -std=c++14 main.cpp -o main

编译器开始像 VSCode 一样显示错误。

很明显,这不是错误,如何更改VSCode使用的C++版本?

【问题讨论】:

标签: c++ visual-studio-code c++17 c++14 c++20


【解决方案1】:

我找到了问题的答案。

我使用以下代码:

template <template <typename...> class _Tr, typename... _Args>
std::ostream &operator<<(std::ostream &os, _Tr<_Args...> a)
{
    os << "[ ";
    for (T t : a)
    {
        os << t << " ";
    }
    os << "]";
    return os;
}

我试过了,它适用于 -std=c++14map, multimap, set, multiset, vector, unordered_map, unordered_set

类 Python 版本

template <template <typename...> class _Tr, typename... _Args>
std::ostream &operator<<(std::ostream &os, _Tr<_Args...> a)
{
    os << "[";
    auto s = a.begin();
    auto e = a.end();
    e--;
    for (auto it = s; it != a.end(); it++)
    {
        cout << *it << (it == e ? "" : ", ");
    }
    os << "]";
    return os;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-24
    • 2015-07-28
    • 2022-10-14
    • 1970-01-01
    • 2018-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多