Here is my code:
#include <iostream>
int main(int argc, char const *argv[])
{
std::string s = "hello";
std::cout << s.size() << std::endl;
return 0;
}
To my surprise, I can compile and run it with clang++
, though I even don't add #include <string>
.
So, is it necessary to add #include <string>
in order to use std::string
?
Because the declaration of class string is in the namespace std. Thus you either need to always access it via std::string (then you don't need to have using) or do it as you did.
There is no functionality difference between string and std::string because they're the same type.
The std::string class manages the underlying storage for you, storing your strings in a contiguous manner. You can get access to this underlying buffer using the c_str() member function, which will return a pointer to null-terminated char array. This allows std::string to interoperate with C-string APIs.
C-strings are usually faster, because they do not call malloc/new. But there are cases where std::string is faster. Function strlen() is O(N), but std::string::size() is O(1). Also when you search for substring, in C strings you need to check for '\0' on every cycle, in std::string - you don't.
Your implementation's iostream
header includes string
. This is not something which you can or should rely on. If you want to use std::string
, you should always #include <string>
, otherwise your program might not run on different implementations, or even in later versions of your current one.
In short: yes, it is necessary.
Parts of standard library often use other parts, so <string>
was included somehow through <iostream>
, and your code compiles nicely.
If you accidentally decide that you don't need <iostream>
anymore and remove that include, <string>
will be implicitly removed, too, and you get a confusing compilation error. That's why it is a good practice to put all necessary includes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With