这可能与您配置的编译环境有关。
以我的为例:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
vector<string> msg {"Hello", "C++", "World", "from", "VS Code", "and the C++ extension!"};
for (const string& word : msg) {
cout << word << " ";
}
cout << endl;
}
如果在在线编译器中编译成功,那么就能成功运行。
eg:programiz:
https://www.programiz.com/cpp-programming/online-compiler/
此外,输出内容为:
Hello C++ World from VS Code and the C++ extension!
但如果编译器在Visual Studio Code中,那么你将面临相同的问题。
“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”
怎么会发生这种情况?或者说,到底发生了什么?
我从来没有配置过这些文件,例如:"launch.json"
,"c_cpp_properties.json"
。
我在下载 VS Code 和 C/C++ 插件后直接编译。
我认为解决问题的关键是确保已经配置好了编译环境。
例如:如果 IDE 出现问题,则可以将其迁移到在线编译器中进行测试是否能够成功编译。
如果和我一样,在没有配置文件的情况下仍然出现相同的问题,那么问题的根本原因就是配置文件配置失败。
最后,Visual Studio Code 在 macOS 中配置 C/C++ 编译环境文件比较困难,但是可以解决。
另外,也许这与您的 C++ 语言版本有关。
Use g++ -std=c++11 <filename> when compiling.
使用这个命令来运行你的代码会更好:
g++ -g -Wall -std=c++11 helloworld.cpp
或者,您可以在VS Code中配置tasks.json:
"args": [
"-g",
"-Wall",
"-std=c++11",
"-stdlib=libc++",
"-g",
"${file}",
"-o",
"${fileDirname}/${fileBasenameNoExtension}"
],
在任务的"args"
中添加"-g"
和"-Wall"
。
简而言之,
首先,
报告了这个错误是因为C++98不允许您在初始化向量容器时指定初始元素值。
这是在C++11中,您需要配置c++11支持。
- 如果您的问题出现在VS Code中,则需要在
.vscode/task.json
中配置c++11支持,加上-std=c++11
,-stdlib=libc++
配置。
其次,
如果您还在VS代码中使用C/C++ Clang命令适配器插件,
由于C/C++ Clang命令适配器插件默认未配置为支持C++11,
您还需要配置c++11支持。
1.点击Code
->Preferences
->Settings
,搜索Clang: Cflags
,Clang: Cxxflags
并添加C++11配置;
2.Clang: Cflags
添加项:"-std=c11"
,Clang: Cxxflags
添加项:"-std=c++11"
。
第三,
您还需要C++11运行环境配置。
点击Code Runner
⚙的齿轮(或直接右键单击)以打开扩展设置;
找到Code-runner: Executor Map
并单击Edit in settings.json
;
在"code-runner.executorMap"
中找到"cpp"
行;
将-std=c++11
添加到$fileNameWithoutExt
的末尾,并保存以供使用。
或者,
1.编辑您的环境配置./vscode/setting.json/
;
2.找到"code-runner.executorMap":
;
3.在"code-runner.executorMap":
中找到"cpp"
;
4.在$fileNameWithoutExt
和&& $dir$fileNameWithoutExt
之间添加-std=c++11
就像这样:
![enter image description here](https://istack.dev59.com/mp1kP.webp)
#include <vector>
? - Brian Bistd::vector<int> v = {1,2,3};
和std::vector<std::string> v = {"one", "two", "three"};
,然后回报结果。 - 101010