-10

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;
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
Kenny
  • 355
  • 1
  • 5
  • 14

2 Answers2

3

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.

cadaniluk
  • 15,027
  • 2
  • 39
  • 67
-2

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)

guest
  • 23
  • 1
  • 6
    dont do `using namespace std`, just `using std::vector` is enough – 463035818_is_not_an_ai Dec 26 '15 at 17:12
  • 1
    For serious programs `using namespace std;` is considered bad practice. Here is an explanation: https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice – Galik Dec 26 '15 at 18:31