简体   繁体   English

有谁知道endl(cout)和cout << endl之间的区别?

[英]Does anyone know the difference between endl(cout) and cout << endl?

I thought they were the same thing, but when I sent a code to an online judge (with endl(cout) ) it gave me "Wrong answer" verdict, then I tried to send another with cout << endl and the judge accepted the code! 我认为他们是同一个东西,但是当我向在线法官发送代码时(带有endl(cout) )它给了我“错误的答案”判决,然后我试图用cout << endl发送另一个,并且法官接受了码! Does anyone know the difference between those commands? 有谁知道这些命令之间的区别?

There is none that I know of. 没有我知道的。

std::endl is a function that take a stream and return a stream: std::endl是一个获取流并返回流的函数:

ostream& endl ( ostream& os );

When you apply it to std::cout , it just applies the function right away. 当你将它应用于std::cout ,它只是立即应用该函数。

On the other hand, std::basic_ostream has an overload of operator<< with the signature: 另一方面, std::basic_ostream有一个operator<<的重载,带有签名:

template <typename C, typename T>
basic_ostream<C,T>& operator<<(basic_ostream<C,T>& (*pf)(basic_ostream<C,T>&));

which will also apply the function right away. 这也将立即应用该功能。

So, technically, there is no difference, even though stream std::cout << std::endl is more idiomatic. 因此,从技术上讲,即使stream std::cout << std::endl更具惯用性,也没有区别。 It could be that the judge bot is simplistic though, and does not realizes it. 可能是法官机器人虽然过于简单,但并没有意识到这一点。

The only difference is that endl(cout) is considered as a global function whereas in cout << endl , endl is considered as a manipulator. 唯一的区别是endl(cout)被认为是一个全局函数,而在cout << endlendl被认为是一个操纵器。 But they have the same effect. 但它们具有相同的效果。

Answers above are correct! 上面的答案是正确的! Also, Depending whether you use << endl; 另外,取决于你是否使用<< endl; or endl(cout) it could reduce the number of lines in your code. 或者endl(cout)它可以减少代码中的行数。

Example: 例:

You can have something like: 你可以有类似的东西:

cout << "Hello World" << endl;

OR 要么

cout << "Hello World";

endl(cout);

HOWEVER, cout << "Hello World" << endl(cout); 但是, cout << "Hello World" << endl(cout); //Does NOT work //不起作用

So it is 2 lines vs 1 line in this example. 所以在这个例子中它是2行对1行。

There is no difference in behaviour between those two forms. 这两种形式之间的行为没有区别。 Both refer to the same endl function, which can be used as a manipulator ( cout << endl ) or as a free function ( endl(cout) ). 两者都引用相同的endl函数,它可以用作操纵器( cout << endl )或自由函数( endl(cout) )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM