2

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.

  • 1
    `using namespace std; // this is a using directive telling the compiler to check the std namespace when resolving identifiers with no prefix` -- https://www.learncpp.com/cpp-tutorial/naming-conflicts-and-the-std-namespace/ – Robert Harvey May 23 '19 at 00:12
  • 3
    In *all* cases you need to use `#include `, not just because it doesn't compile. Another header might include it, but there are no guarantees. – Retired Ninja May 23 '19 at 00:18
  • `std:vector` one semi-colon is a `label`. – Raindrop7 May 23 '19 at 00:50

6 Answers6

5

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.

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.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • Why do you mean "for anything that I know"? – Hasan Hussaini May 23 '19 at 00:25
  • actually i understand what your saying now! Thanks so much!! – Hasan Hussaini May 23 '19 at 00:28
  • @HasanHussaini: "I" in this case is referring to the compiler; the directive says "anything the compiler knows in about `std` need not be qualified with `std` by the programmer". I was speaking somewhat informally using "I" and "you", sorry if that confused. – ShadowRanger May 23 '19 at 00:29
  • This only answers half the question. Why don't the other code samples need the include? – Mooing Duck May 23 '19 at 00:33
  • @MooingDuck: I mentioned that in passing when I said "without the `#include ` (directly or indirectly via some other `#include`), the compiler has no idea `std::vector` exists in the first place." The answer to why some code samples work without the include is that they included some other header which in turn includes ``. If they don't, then there is no definition of `std::vector`, and the code fails with undefined types. It must be included, but that doesn't mean you included it directly (that said, you should, to avoid header changes breaking compilation). – ShadowRanger May 23 '19 at 00:37
  • @ShadowRanger: That's a great explanation. Put it in the answer please :D – Mooing Duck May 23 '19 at 17:04
2

Why don't you have to include < vector > if you already include using namespace std

Take a look at this url: https://en.cppreference.com/w/cpp/header

There are more than 100 header files available for your use.

IMHO, the confusion you are experiencing is that these same 100+ header are ALSO available for the header authors, and they also have access to headers not usually published in the standard. The result is that, for instance, when you or I include < stringstream >, some indirect part of that include might also 'pull-in' < string >.

I recommend you do not put "using namespace std" in your code. It's use did not intentionally cause the 'hidden / indirect' include of < vector >, and maybe won't on the next implementation.

I'm on g++v7.3. I'll soon be upgrading to current g++ (I think 9.x?) You can not rely on < vector > being included unless you explicitly include it.

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

Just luck ... I think bad, if you start multiple bad habits because of it.


If your compiler supports -std=c++17 or better, it has a new feature I like. The new feature allows me to, immediately after the header include, specify which function in that library I specifically need. It looks like this:

#include <iostream>
using std::cout, std::cerr, std::endl, std::flush,
      std::hex, std::dec, std::cin;

#include <iomanip>
using std::setw, std::setfill;

#include <string>
using std::string, std::to_string;

#include <thread>
using std::thread, std::this_thread::sleep_for;

#include <vector>
using std::vector;

Your own libraries can be handled similarly:

#ifndef                 DTB_ENG_FORMAT_HH
#include "../../bag/src/dtb_eng_format.hh"
using DTB::EngFormat_t;
#endif

#ifndef                 DTB_PPLSEM_HH
#include "../../bag/src/dtb_pplsem.hh"
using DTB::PPLSem_t;
#endif

#ifndef                 DTB_ENG_FORMAT_HH
#include "../../bag/src/dtb_eng_format.hh"
#endif

#ifndef                 DTB_ASSERT_HH
#include "../../bag/src/dtb_assert.hh"
#endif

I try to keep track of a smalle set of these, and collect them in a file. I use the bigger lists when I am starting a new effort, and trivially remove the 'unused' functions (when I want to post my efforts).

2785528
  • 5,438
  • 2
  • 18
  • 20
  • Thanks for the heads up. In own VS setup there's `` which pulls in ``, where the risk of not including `` comes at the cost of hoping it won't be pulled from `` during the lifetime of the code. – Laurie Stearn Jan 17 '20 at 12:06
1

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

You have to include <vector> only if you use the declarations from that header. Otherwise you don't need to include it. You don't ever need using namespace std;.

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

You always have to include <vector> if you create std:vector<int> objects.

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

No, The standard library doesn't use using namespace std;. If it did, that would invalidate the whole point of using the std namespace.

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

This is because you cannot declare a variable of a type that hasn't been defined. The definition of std::vector is in <vector>

Community
  • 1
  • 1
eerorika
  • 232,697
  • 12
  • 197
  • 326
0

#include <some_file> just replaces the #include directive with the contents of the file "some_file".

In the case of #include <vector>, the file "vector" contains the definition of the class template vector in the std namespace. To declare an instance of a class, that class's definition must be visible to the compiler, so to declare std::vector<int> foo you must #include <vector>, either directly or indirectly by #includeing another file that #includes it.

So why do some code samples have to #include <vector> and others don't? Well, they all do. Some may not #include it explicitly, but they must #include another file that does #include <vector>.

Of course, in many example snippets people will simply omit the #includes for brevity. The code won't compile without the proper #includes, but they make the code longer and may distract from the point the author is trying to make.


The statement using namespace std; just tells the compiler that it should search the std namespace for any unqualified names it can't find in the current namespace. That means that the compiler can find the vector class by both the names vector and std::vector.

Miles Budnek
  • 28,216
  • 2
  • 35
  • 52
  • 1
    This only answers half the question clearly, and only hints at the answer to the other half. Why don't the other code samples need the include? – Mooing Duck May 23 '19 at 00:32
0

First, std:vector<int> - //blah, a vector is created. won't compile because you used a single colon : which means that std here is a label declaration. and a label name cannot be vector<int>. So I guess you meant: std::vector<int>.

Second, As you may know vector, iostream,... are library types defined in headers <vector>, <iotream> respectively... To use these types you must include these headers first either directly or indirectly.

namespace std in C++ is a grouping of identifiers that is used to reduce the possibility of naming collisions. In modern C++, all of the functionality in the C++ standard library is now defined inside namespace std (short for standard).

Look for example at std::cout; this identifier is declared in namespace std whose type is ostream. So to you must include iostream first so that the compile can see what ostream object is and then tell the compiler where this object is declared? in namespace std. So including only iostream is not sufficient thus you either add the whole content of namespace std in which cout is declared, or just tell the compiler explicitly where cout is declared through fully qualifying it:

#include <iostream> // contains output/input library types definitions
using std::cout; // ok add only cout definition to the program not the whole content of std.
using namespace std; // contains cout, cin, vector....
Raindrop7
  • 3,889
  • 3
  • 16
  • 27
-1

Vectors are part of the C++ STL, yes, but you need to include the <vector> header file to be able to use it. It's the same reason why you need to #include <string> if you want to use STL strings. After you include these headers, you need to use the std:: namespace identifier before declaring a vector or string, so that the compiler knows that what you're declaring is part of the C++ STL and not built-in to "base" C or C++.

Somewhat basically, what using namespace std does is give you the ability to drop the std:: qualifier before your string or vector or whatever. This isn't recommended, here's an article briefly explaining why you shouldn't be using it. Instead, if you want to clean up your code and don't want to type std:: every time you want to print to the console, then consider importing single identifiers, for example using namespace std::cout instead.

Hope this helps.

ddlkkd
  • 25
  • 1
  • 6
  • 1
    This only answers half the question. Why don't the other code samples need the include? – Mooing Duck May 23 '19 at 00:33
  • As has been mentioned in other answers, other people's code could be including headers that have vectors, but there are no guarantees – ddlkkd May 23 '19 at 00:41
  • By Sergey Zubkov from https://www.quora.com/In-C-what-is-stl-and-std-How-are-they-different : “STL” (“standard template library”) was the name of a Hewlett-Packard’s C++ library in the early 1990s. It was hugely influential in the development of the C++ standard library in 1998, and that was its undoing: HP saw no need to maintain STL, it spend over a decade abandoned on SGI’s website, and is now gone." ....Your conforming compiler (such as g++ 9.2.1 on Lubuntu 19.10) comes with the "C++ standard library" and you should be using it (not the abandoned STL). i.e. 'vector' is included. – 2785528 Jan 18 '20 at 21:21