quot;Permanentquot; std::setw(“永久标准::设置)
问题描述
有没有办法永久设置 std::setw
操纵器(或其功能 width
)?看看这个:
Is there any way how to set std::setw
manipulator (or its function width
) permanently? Look at this:
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <iterator>
int main( void )
{
int array[] = { 1, 2, 4, 8, 16, 32, 64, 128, 256 };
std::cout.fill( '0' );
std::cout.flags( std::ios::hex );
std::cout.width( 3 );
std::copy( &array[0], &array[9], std::ostream_iterator<int>( std::cout, " " ) );
std::cout << std::endl;
for( int i = 0; i < 9; i++ )
{
std::cout.width( 3 );
std::cout << array[i] << " ";
}
std::cout << std::endl;
}
运行后,我看到:
001 2 4 8 10 20 40 80 100
001 002 004 008 010 020 040 080 100
即除了必须为每个条目设置的 setw
/width
之外,每个操纵符都保持自己的位置.有没有什么优雅的方法可以将 std::copy
(或其他东西)与 setw
一起使用?我所说的优雅当然不是指创建自己的函子或函数来将内容写入 std::cout
.
I.e. every manipulator holds its place except the setw
/width
which must be set for every entry. Is there any elegant way how to use std::copy
(or something else) along with setw
? And by elegant I certainly don't mean creating own functor or function for writing stuff into std::cout
.
推荐答案
好吧,这是不可能的.没有办法让它每次都调用 .width
.但是你当然可以使用 boost:
Well, it's not possible. No way to make it call .width
each time again. But you can use boost, of course:
#include <boost/function_output_iterator.hpp>
#include <boost/lambda/lambda.hpp>
#include <algorithm>
#include <iostream>
#include <iomanip>
int main() {
using namespace boost::lambda;
int a[] = { 1, 2, 3, 4 };
std::copy(a, a + 4,
boost::make_function_output_iterator(
var(std::cout) << std::setw(3) << _1)
);
}
它确实创建了自己的函子,但它发生在幕后:)
It does create its own functor, but it happens behind the scene :)
这篇关于“永久"标准::设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:“永久"标准::设置


基础教程推荐
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 使用从字符串中提取的参数调用函数 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 从 std::cin 读取密码 2021-01-01