我对 C++ 中的 Vector 有疑问。
当我尝试用它们做基本的事情时,我的程序“不起作用”了。
在 Stack Overflow 上搜索但没有找到相关内容。
但我对这个话题了解不多,所以我有点坚持下去。
示例:
#include <iostream>
#include <vector>
int main(int argc, char ** argv){
std::cout << "Hello world\n";
std::vector< int > arr;
}
这个程序将输出“Hello world”,因为我不与向量交互。
但如果我这样做:
#include <iostream>
#include <vector>
int main(int argc, char ** argv){
std::cout << "Hello world\n";
std::vector< int > arr;
arr.push_back(1);
}
例如,没有 STDOUT。 Hello world 永远不会被“打印”。并且没有错误。 我使用 Visual Studio 代码并使用以下命令编译我的程序
g++ -o progam -Wall main.cpp
命令
g++ -o -Wall main.cpp
将创建一个名为-Wall
的可执行文件。除非那是您想要运行的程序,否则它不会工作。
相反,您需要类似
g++ -o program -Wall main.cpp
的内容,然后运行 program
。在这种情况下,你的两个例子都做了正确的事情。
我在 VSCode 1.72.2 和 g++ 12.1.0 中也遇到了这个问题(或非常相似的问题)。我的解决方法是将
"-static-libstdc++"
添加到 tasks.json
中的编译器参数。
追踪此问题的一些额外面包屑: 从 VSCode 终端或 powershell 安静地运行编译后的程序似乎没有执行任何操作。从命令提示符执行它会出现一个弹出对话框:
The procedure entry point _ZSt28__throw_bad_array_new_lengthv could not be located in the dynamic link library ...
谷歌搜索导致this thread,其中@Thinker-101给出了有用的编译器参数。
我创建了一个向量,它告诉我存在错误,因为这是预期的;
#include <iostream>
#include <vector>
using namespace std;
int main(){
vector <int> record {12,2,23,23}; //I get a missing ; after record. I don't know why this happens. I'm running it with RunCode on a Macboock Pro M1
cout<< record[2];
}