如果您已经包含使用名称空间 std,为什么不需要 #include<vector>?

Has*_*ini 2 c++ stl vector stdvector

我一直在学习面向对象的计算,特别是迭代器和标准模板库等。

我似乎不太明白为什么如果你写

std:vector<int> - //blah, a vector is created.
Run Code Online (Sandbox Code Playgroud)

但是,在某些情况下,您需要编写

#include <vector> //to include vector library
Run Code Online (Sandbox Code Playgroud)

为什么是这样?我们通常编写“使用命名空间 std”的标准库是否已经包含向量库?

当我删除定义文件#include 时,计算机无法识别我的向量变量。

但是,我在某些情况下看到很多人使用了 vector 函数,而没有使用 std::vector 来实际声明它???

std::vector<int>::iterator pos;
std::vector<int>coll;
Run Code Online (Sandbox Code Playgroud)

这是其他人使用的代码,它似乎有效?

#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector>

using namespace std;

int main() {
vector<int>::iterator pos;
vector<int>coll;
}
Run Code Online (Sandbox Code Playgroud)

// 这对我有用,但我想了解为什么这个有效而另一个无效。

Sha*_*ger 5

该using namespace std;指令只是说“对于我所知道的std命名空间中的任何内容,您都可以省略std::前缀”。但是如果没有#include <vector>(直接或间接通过其他#include),编译器std::vector首先不知道存在。

标头为您提供各种类和 API 的声明(在某些情况下,还有定义);该using namespace声明只是消除了使用命名空间前缀显式限定对它们的引用的需要。

您仍然需要执行#includes 的原因是关于声明的冲突(您不想只包含每个可能的包含文件,因为其中一些可能对某些名称有冲突的定义)和编译性能(#include世界意味着要编译数千字节(如果不是兆字节)的额外代码,其中绝大多数您实际上不会使用;将其限制为您实际需要的标头意味着更少的磁盘 I/O、更低的内存和更低的 CPU 时间来执行编译)。

以供将来参考,“我们通常写'using namespace std;'的地方”表明您被教导了坏习惯。using namespace std; 在生产代码中不受欢迎。