我一直在学习面向对象的计算,尤其是迭代器和标准模板库等。
我不太明白为什么要写
std:vector<int> - //blah, a vector is created.
但是,在某些情况下你需要这样写
#include <vector> //to include vector library
这是为什么? 我们通常写“using namespace std”的标准库是否已经包含 vector 库?
当我删除定义文件#include 时,计算机无法识别我的 vector 变量。
但是,我在某些情况下看到很多人使用了 vector 函数而没有通过使用 std::vector 实际声明它???
std::vector<int>::iterator pos;
std::vector<int>coll;
这是其他人使用的代码,而且似乎有效?
#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector>
using namespace std;
int main() {
vector<int>::iterator pos;
vector<int>coll;
}
//这对我有用,但我想了解为什么这个有效而另一个无效。
最佳答案
using namespace std;
指令只是说“对于我所知道的 std
命名空间中的任何内容,您可以省略 std::
前缀”。但是没有 #include <vector>
(直接或间接通过其他一些 #include
),编译器不知道 std::vector
存在于第一位。
header 为您提供各种类和 API 的声明(在某些情况下为定义); using namespace
声明只是消除了使用 namespace 前缀明确限定对它们的引用的需要。
您仍然需要执行 #include
的原因s 是关于消除声明的冲突(你不想只包含每个可能的包含文件,因为其中一些可能对某些名称有冲突的定义)和编译性能( #include
ing 世界意味着很多千字节,如果不是兆字节的话,要编译的额外代码,其中绝大多数您实际上不会使用;将其限制为您实际需要的 header 意味着更少的磁盘 I/O、更低的内存和更少的 CPU 时间来执行编译)。
为了将来引用,“我们通常写‘using namespace std;’的地方”表示您已经养成了坏习惯。 using namespace std;
is frowned upon in production code .
关于c++ - 如果您已经包含使用 namespace 标准,为什么不必#include<vector>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56266499/