I am new to C++ and trying to figure out how to use vector
.
More specifically, I want to know when I need to use #include
. I
You may see code that does not #include <vector>
directly. But if you inspect the preprocessed code I'm certain you'll find that that code did include the header - but indirectly through some other header.
This is fragile and you shouldn't do it. But that doesn't mean it does not work.
When you see code that uses std::vector
, but did not #include <vector>
, that code is broken. Period.
It may "just so happen" to work on particular compilers/standard library implementations/platforms/planets, depending on which other standard headers "just so happen" to already be including <vector>
for their own use. This shall not be relied upon.
You need to include the header file, to use any type of data/function. All the data types and functions in c++ are included in their own libraries.If you dont include the library, the c++ program won't know what you used, because it doesnt know they even excist.Its like :
You want to play with Jim's dog, but you dont know who Jim is, or what a dog is.
vector
is not actually built into C++, it is only part of its standard library which is guaranteed to be available to you if you use C++. vector
(or, by its full name, std::vector
) is itself implemented in C++.
By writing #include <vector>
, you are telling the compiler to not only use your own code, but to also compile a file called vector
. This file is actually somewhere on your harddrive (if you use GNU/Linux, it's probably located at /usr/include/c++/[GCC_VERSION]/vector
).
You cannot use std::vector
without including that file, because the compiler then doesn't know a class called std::vector
. The compiler only knows the language C++, not its standard library!
If some programs use std::vector
without including its header file, it's because some header file that they have already included, has an #include <vector>
somewhere. There may be good reasons for that (e.g. some C++ courses ship with a file that includes all necessary headers and that is used in the first few lessons). However there may also be standard library headers that include vector
(some implementations of iostream
do that). Relying upon that is not a good idea because it differs from implementation to implementation, so your program might work in Visual C++ 2010, but it doesn't compile on GNU or in a newer version of Visual C++.