Printing string through ostringstream is faster than printing directly string ?

Revision en2, by nhannguyen95, 2016-09-02 05:40:27

Let's take a look at my 2 submissions for problem 681C

20333485 — TLE, don't use ostringstream

20333517 — AC, use ostringstream

Briefly, the answer of the problem is a string has 1e6 lines, each line has maximum 20 characters.

In the first submission, I stored the answer in string res, then I sum "res = res + line". Finally I printed "cout << res" and got TLE

But in the second submission, I stored the answer in sout object ( an ostringstream), sum "sout << line", and printed "cout << sout.str()" and got AC ( even 4 times faster than the first submission)

I don't understand the reason behind this. Anyone could explain it ?

Thank you in advance

Tags string, ostringstream, tle

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en2 English nhannguyen95 2016-09-02 05:40:27 2 Tiny change: 's maximum 10 characte' -> 's maximum 20 characte'
en1 English nhannguyen95 2016-09-02 05:28:34 927 Initial revision (published)