[英]how to use iostream more efficiently in cpp forloop?
I have some following code.我有一些以下代码。 In order to limit call times of
operator << to std::cout
.为了将
operator << to std::cout
。 I use an std::ostream outside forloop.我在 forloop 之外使用 std::ostream 。 But I get compile errors.
但我得到编译错误。
#include <iostream>
int square(int num) {
std::ostream os;
for (int i=0; i<10; i++) {
os << "test: i," << std::endl;
}
std::cout << os;
return 0;
}
In file included from /opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/iostream:39:0,
from <source>:2:
/opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/ostream: In function 'int square(int)':
/opt/compiler-explorer/gcc-5.5.0/include/c++/5.5.0/ostream:384:7: error: 'std::basic_ostream<_CharT, _Traits>::basic_ostream() [with _CharT = char; _Traits = std::char_traits<char>]' is protected
basic_ostream()
^
<source>:6:18: error: within this context
std::ostream os;
^
Compiler returned: 1
Does the smart code with efficiency exist?有效率的智能代码存在吗?
Let me make my intension clear.让我把我的意图说清楚。
I don't want to call api and write date to std::cout by multiple times in a loop.我不想在循环中多次调用 api 并将日期写入 std::cout 。 I know that I can use a string buffer to receive data multiple times, and finally print to std::cout.
我知道我可以使用字符串缓冲区多次接收数据,最后打印到std::cout。 But this also takes the cost of creating a string.
但这也需要创建字符串的成本。 Is there any directly use of the api or structure provided by <iostream> to write better code?
有没有直接使用 api 或 <iostream> 提供的结构来编写更好的代码?
I'm not sure about efficiency, but what you want to do looks like using std::stringstream
.我不确定效率,但你想做的事情看起来像使用
std::stringstream
。
#include <iostream>
#include <sstream>
int square(int num) {
std::stringstream ss;
for (int i=0; i<10; i++) {
ss << "test: i," << std::endl;
}
std::cout << ss.str();
return 0;
}
If you want efficiency, you there are a few things you could do.如果你想要效率,你可以做一些事情。
If you want to keep using iostreams, you should take a look at std::ios_base::sync_with_stdio , it can make std::cout
much faster, but you wouldn't be able to use C functions to read/write from streams.如果你想继续使用 iostreams,你应该看看std::ios_base::sync_with_stdio ,它可以使
std::cout
更快,但你不能使用 C 函数从流中读/写。 You also shouldn't use std::endl
, as it forces a stream flush, use '\n'
instead.您也不应该使用
std::endl
,因为它会强制 stream 刷新,请改用'\n'
。
#include <iostream>
int square(int num) {
for (int i=0; i<10; i++) {
std::cout << "test: " << i << '\n';
}
return 0;
}
int main(){
std::ios_base::sync_with_stdio(false);
...
}
You could also use an external library, fmt is amaizing for that.您也可以使用外部库, fmt对此非常满意。
#include <fmt/core.h>
int square(int num) {
for (int i=0; i<10; i++) {
fmt::print("test: {}\n", i);
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.