【发布时间】:2017-12-30 17:56:09
【问题描述】:
我有这个简单的 C++ 代码。它在 Microsoft Visual Studio 2017 中正确执行。
// Author: Herbert Schildt
// Modified: Qiang Hu
// File name: ~ftp/pub/class/cplusplus/Array/Array3.cpp
// Purpose: Use sqrs[][] -- two dimentional integer
// array to store integers from 1 to 10 and
// their squares.
// Ask user for a number, then look up this
// number in the array and then print out its
// corresponding square.
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// C++ allows for the initialization of arrays. In the following,
// we are initializing a 10x2 integer array. After initialization,
// sqrs[0][0] = 1
// sqrs[0][1] = 1
// sqrs[1][0] = 2
// sqrs[1][1] = 4
// and so on
vector<vector<int> > sqrs = { {1, 1},
{2, 4}, // The square of 2 is 4,and so on
{3, 9},
{4, 16},
{5, 25},
{6, 36},
{7, 49},
{8, 64},
{9, 81},
{10, 100}
};
int i, j;
cout << "Enter a number between 1 and 10: ";
cin >> i;
// look up i
for(j = 0; j < 10; j++)
if(sqrs[j][0] == i) break; // break from loop if i is found
cout << "The square of " << i << " is " ;
cout << sqrs[j][1] << endl;
return 0;
}
我尝试在windows下使用VSCode编译相同的代码,但代码不执行。它给了我以下错误。
Untitled-2.cpp: In function 'int main()':
Untitled-2.cpp:34:19: error: in C++98 'sqrs' must be initialized by constructor, not by '{...}'
};
^
Untitled-2.cpp:34:19: required from here
Untitled-2.cpp:34:19: warning: extended initializer lists only available with -std=c++11 or -std=gnu++11
我猜VSCode使用的编译器不是C++11而是C++98。如果是这种情况,我该如何将编译器更改为 C++11。 (在这里,我一直在寻找解决方案,但从未找到有用的东西。)如果没有,如何解决这个问题?
【问题讨论】:
-
您是否检查过您的 c++ 环境并确保它已添加到您的 PATH 中。
-
这取决于,您配置
VSCode使用什么编译器?看起来像 g++,所以将它在最后一个警告中所说的添加到构建开关中。 -
我安装了 MinGW 并使用它。但是我可以使用与 VS2017 相同的编译器吗?
-
很多帖子:谷歌:“为 c++ 设置 Visual Studio 代码”
-
VSCode 正确执行代码(如果我在上面的代码中将
vector更改为array,它将正常工作)。问题不在于如何设置 VSCode 来运行 C++ 代码。问题是 VSCode 使用的编译器不知道如何像我一样初始化vector。所以我认为这可能是C++版本的问题。
标签: c++ visual-studio c++11 visual-studio-code