关于 c++ 中 std::cout 的效率以及打印消息的替代方法
我正在学习 C++,作为练习,我正在实现一个粗略的 ASCII 渲染器,我的渲染函数看起来像这样:
void render() {
for(int y = 0;y < height;y++) {
for(int x = 0;x < width;x++) {
std::cout << getCharOfPixel(x, y);
}
std::cout << '\n';
}
}
但我想知道将整个内容存储在字符串中并打印出整个内容是否会更有效一次字符串,如下所示:
void render() {
std::string finalString((width + 1) * height, '\0'); // initializing the string with ((width + 1) * height) null characters, to avoid resizing efficiency lack
int characterIndex = 0; // where we are writing to finalString
for(int y = 0;y < height;y++) {
for(int x = 0;x < width;x++) {
finalString[characterIndex++] = getCharOfPixel(x, y);
}
finalString[characterIndex++] = '\n';
}
std::cout << finalString;
}
更具体地说,我问 std::cout 的效率是否取决于我正在写入的字符数或调用它的次数
I'm learning C++, and as a exercise i am implementing a crude ASCII renderer, and my render function looks something like this:
void render() {
for(int y = 0;y < height;y++) {
for(int x = 0;x < width;x++) {
std::cout << getCharOfPixel(x, y);
}
std::cout << '\n';
}
}
but i wonder if it could be more efficient to store the whole thing in a string and just print out the whole string at once, like this:
void render() {
std::string finalString((width + 1) * height, '\0'); // initializing the string with ((width + 1) * height) null characters, to avoid resizing efficiency lack
int characterIndex = 0; // where we are writing to finalString
for(int y = 0;y < height;y++) {
for(int x = 0;x < width;x++) {
finalString[characterIndex++] = getCharOfPixel(x, y);
}
finalString[characterIndex++] = '\n';
}
std::cout << finalString;
}
more specifically, I'm asking if the efficiency of std::cout depends on how many characters i am writing or how many times i invoke it
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论