Search code examples
c++vectorstlstdvector

Why does dont you have to #include<vector>, if you already include using name space std?


I have been learning about object orientated computing and in particular iterators and standard template libraries etc.

I don't quite seem to understand why if you write

std:vector<int> - //blah, a vector is created.

However, in some cases you need to write

#include <vector> //to include vector library

Why is this? Does the standard library where we usually write "using namespace std" - already include the vector library?

When I remove the definition file #include, then the computer cannot recognize my vector variables.

However, I have seen in some cases that many people have used the vector function without actually declaring it by using std::vector???

std::vector<int>::iterator pos;
std::vector<int>coll;

this is the code other people use and it seems to work?

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

using namespace std;

int main() {
vector<int>::iterator pos;
vector<int>coll;
}

// this works for me, but I want to understand why this one works and the other one doesn't.


Solution

  • The using namespace std; directive just says "For anything in the std namespace that I know about, you can leave off the std:: prefix". But without the #include <vector> (directly or indirectly via some other #include), the compiler has no idea std::vector exists in the first place. The reason why some code samples work without the include is that they included some other header which in turn includes <vector>. If they didn't do that, then there is no definition of std::vector, and the code fails with undefined types. <vector> must be included, but indirect inclusion via some other include is enough (that said, you should always #include it directly if you're using std::vector, to avoid potential header changes, or differences between implementations, breaking compilation).

    Headers give you the declarations (and in some cases, definitions) of various classes and APIs; the using namespace declaration just removes the need to explicitly qualify your references to them with a namespace prefix.

    The reason you're still required to perform the #includes is about deconfliction of declarations (you don't want to just include every possible include file, because some of them might have conflicting definitions of certain names), and compilation performance (#includeing the world means many kilobytes, if not megabytes, of additional code to compile, the vast majority of which you won't actually use; limiting it to the headers you actually need means less disk I/O, lower memory and lower CPU time to perform compilation).

    For future reference, "where we usually write 'using namespace std;'" indicates you've been taught bad habits. using namespace std; is frowned upon in production code.