I wonder what is the difference between std::basic_ostream<CharT,Traits>::operator<<
and std::basic_ostream<CharT,Traits>::write
. What about performance?
#include <iostream>
#include <string>
int main()
{
std::string tempMsg;
tempMsg.reserve( 100 );
tempMsg += "This is a string";
std::cout.write( tempMsg.data( ), tempMsg.size( ) ).write( "\n", 1 );
std::cout << tempMsg << '\n';
}
They both print the same string. But what are the advantages of each of them?
The function allows to specify the number of characters to be outputted for a character array.
For example of you have declaration
const char *s = "Hello World!";
and want to output only the word "Hello" from the string literal then you can write
std::cout.write( s, 5 );
If you will write
std::cout << s;
then the whole string literal will be outputted.
Thus using the function you can output any part of a character array as for example
std::cout. write( s + 6, 2 ) << 'w' << s + 11 << '\n';
As for the performance then there is no difference or the difference is insignificant. What is important is the functionality.