I am a little confused about the use of vector. We usually type
#include <vector>
first. Then why we still need to attach the name space of vector when using it, like:
std::vector<int> a;
Why not just
vector<int> a;
I am a little confused about the use of vector. We usually type
#include <vector>
first. Then why we still need to attach the name space of vector when using it, like:
std::vector<int> a;
Why not just
vector<int> a;
Every #include
directive including something from the C++ standard library "loads" the entities into the std
namespace (or some other namespace like this).
The namespace helps preventing global namespace pollution - by keeping everything in a seperate namespace, identifier collisions are rendered impossible.
In the <vector>
file, then there is something like
namespace std {
template<typename T> class vector {
...
};
}
As you see, the vector
template is still in the std
namespace.
In summary, you use an #include
preprocessor directive to use some facility provided in a header file. The file's contents textually replace the #include
directive.
Still, these facilities are in a different namespace to prevent name clashing.
Namespaces were created to avoid collisions in naming. You might have something else as vector
in your code. However you can use using namespace std;
- it would allow you to use it like this (and anything else in std namespace): vector a;
(of course if there is no name collision)