c – 如何更改分隔符的位置?
发布时间:2020-12-16 10:29:56 所属栏目:百科 来源:网络整理
导读:这个例子: #include iostream#include iterator#include algorithmint main(){ int v[] = { 1,2,3 }; std::copy( v[0],v[3],std::ostream_iterator int ( std::cout,"n " ) );} 产生下一个输出: 1 2 3? 有没有办法改变示例以使其产生下一个输出? 1 2 3 P
这个例子:
#include <iostream> #include <iterator> #include <algorithm> int main() { int v[] = { 1,2,3 }; std::copy( &v[0],&v[3],std::ostream_iterator< int >( std::cout,"n " ) ); } 产生下一个输出: 1 2 3 ? 有没有办法改变示例以使其产生下一个输出? 1 2 3 PS我知道我可以使用for循环,但我对使用算法和迭代器的解决方案感兴趣. 解决方法
使用std :: ostream_iterator无法做到这一点. (恕我直言,应该
是的,但它不存在.)如果你不介意写一个额外的小 功能或类, 你可以使用std :: transform,例如: struct FormatString { std::string operator()( std::string const& original ) const { return ' ' + original + 'n'; } }; // ... std::transform( v.begin(),v.end(),std::ostream_iterator<std::string>( std::cout ),FormatString() ); 如果你有C 11,你可以使用lambda作为FormatString. 我发现这种情况的需要经常发生,我已经写了一篇 std::transform( v.begin(),PatsubstTransformer( "%"," %n" ) ); 我发现我经常使用它. (我也发现使用std :: transform更多比std :: copy更合适,因为我输出的是一个转型.) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |