std::string vs string in c++
As the other answer already stated, using std::
is necessary unless you import either the whole std
namespace or std::string
(see below).
In my opinion it's nicer to use std::string
instead of string
as it explicitly shows that it's a std::string
and not some other string implementation.
If you prefer to write just string
though, I'd suggest you to use using std::string;
instead of using namespace std;
to only import the things into the global namespace that you actually require.
The full name of string
is std::string
because it resides in namespace std
, the namespace in which all of the C++ standard library functions, classes, and objects reside.
In your code, you've explicitly added the line using namespace std;
, which lets you use anything from the standard namespace without using the std::
prefix. Thus you can refer to std::string
(the real name of the string type) using the shorthand string
since the compiler knows to look in namespace std
for it.
There is no functionality difference between string
and std::string
because they're the same type. That said, there are times where you would prefer std::string
over string
. For example, in a header file, it is generally not considered a good idea to put the line using namespace std;
(or to use any namespace, for that matter) because it can cause names in files that include that header to become ambiguous. In this setup, you would just #include <string>
in the header, then use std::string
to refer to the string type. Similarly, if there ever was any ambiguity between std::string
and some other string
type, using the name std::string
would remove the ambiguity.
Whether or not you include the line using namespace std;
at all is a somewhat contested topic and many programmers are strongly for or strongly against it. I suggest using whatever you're comfortable with and making sure to adopt whatever coding conventions are used when working on a large project.
As ssteinberg said it is the same. But only syntactically.
From my experience, it is more useful to either use the full name
std::string
wherever you need it, or add an explicit
using std::string;
in the beginning of your source file.
The advantage is that in this way the dependencies of your source file are more observable. If you add a
using namespace std;
it means that your code may depend on anything within that namespace.