即使我包含了必要的 headers,C++ 向量也没有初始化

C++ vectors not initializing even when I included the necessary headers

基本上问题是什么:我无法在 C++ 中初始化任何类型的向量;

这是我的代码:

#include <fstream>
#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main() {

  //The error occurs under the word "lines" in the following line
  vector<string> lines{"Hello", "there", "General", "Kenobi", "you",
                       "are",   "a",     "bold",    "one"};
}

该错误由程序中“行”一词下方的红色波浪线显示。 这是我的错误:

no instance of constructor "std::__1::vector<_Tp, _Allocator>::vector [with _Tp=std::__1::string, _Allocator=std::__1::allocator<std::__1::string>]" matches the argument list -- argument types are: (const char [6], const char [6], const char [8], const char [7], const char [4], const char [4], const char [2], const char [5], const char [4])C/C++(289)
std::__1::vector<std::__1::string> lines

我广泛地查找了这个问题,但找不到一个有用的来源。我遇到的一个资源建议使用另一个 header 文件 (std_lib_facilities.h),即使我添加了它也没有用。我还尝试在所有内容前加上 std:: 前缀,而不是使用 std 作为命名空间,但这也没有做任何事情。

作为最后的手段,我从网上复制了代码的工作示例并尝试 运行 它们,但我每次都遇到相同的、可重现的错误,即使是在创建 int 或 char 向量时也是如此。

我确定我遗漏了一些简单的东西,但我一直无法弄明白。知道的请帮帮我

一如既往,如果您回答或试图回答这个问题,感谢您抽出时间。

编辑:建议的问题是重复的不是。这个问题的解决方案涉及编辑我的 tasks.json 文件,而另一个答案基本上与我的问题无关。

要使用 C++11 编译代码,请将 tasks.json 文件更改为:

{
  "version": "2.0.0",
  "tasks": [
    {
      "type": "cppbuild",
      "label": "C/C++: clang++ build active file",
      "command": "/usr/bin/clang++",
      "args": [
        "-std=c++11",
        "-g",
        "${file}",
        "-o",
        "${fileDirname}/${fileBasenameNoExtension}"
      ],
      "options": {
        "cwd": "${fileDirname}"
      },
      "problemMatcher": [
        "$gcc"
      ],
      "group": "build",
      "detail": "compiler: /usr/bin/clang++"
    }
  ]
}

这将使用 clang++.

使用 C++11 正确编译您的代码

The error is shown by a red squiggly line under the word "lines" in the program.

要摆脱“红色波浪线”,您需要让 IntelliSense 在 VSCode 中正常工作。为此,您需要配置您正在使用的扩展 也可以使用 C++11。

如果您使用的是 Microsoft's C/C++ extension,您需要从菜单转到:File > Preferences > Settings,然后在 C/C++ 中输入在搜索栏中,查找名为 Cpp Standard 的设置,然后在各种 C++ 标准的下拉列表中,select C++11.