无法递归的五点半

for_each(day.begin(),day.end(),bind2nd(Add(),me))

导航

<2006年10月>
24252627282930
1234567
891011121314
15161718192021
22232425262728
2930311234

统计

常用链接

留言簿(4)

随笔分类

随笔档案

文章分类

相册

收藏夹

C++

Unix/Linux

个人主页

其他

软件工程

网络管理

综合

搜索

积分与排名

最新评论

阅读排行榜

评论排行榜

指数函数的模板元编程

在程序中需要将一个正整数(如123)转换成一个固定长的串(如8位,00000123)。算法有很多了。我采用可以这个方法123+10^8=100000123,将100000123转换成串"100000123",然后返回这个串的子串substr(1)。在这个方法当中会涉及指数的运算,C++只能作浮点数的指数运算,为提高效率使用模板元编程,将这一过程提前到编译期完成。程序很简单,大家看看就明白了:

    template
<int d,int pow>
    
struct Power
    {
        
static const int value = Power<d,pow-1>::value * d;
    };

    template
<int d>
    
struct Power<d,0>
    {
        
static const int value = 1;
    };

    
/**
     * 该函数将一个整数转换成固定长度的0不齐的串,如12->"00012"
     
*/
    template
<int len>
    std::
string int_cast_zerostr(const int i)
    {

        std::
string result  = boost::lexical_cast<std::string>(Power<10,len>::value + i);
        
return result.substr(1);
    }

如果要将12转换成"00000012",可使用函数int_cast_zerostr<8>(12)。

谢谢小明的提醒,想起Boost有个format库,所以可以这样
    boost::format f("%08d");
    std::
string s = (f%12).str();
    std::cout
<<s; //s = "00000012"
不过个人更喜欢int_cast_zerostr<8>(12)方式。呵呵!

posted on 2006-10-24 11:09 五点半 阅读(1104) 评论(1)  编辑 收藏 引用 所属分类: 模板元编程

评论

# re: 指数函数的模板元编程 2006-10-24 11:28 小明

char s[32];
int i=12;
sprintf(s,"%08d",i);

then:
s="00000012"  回复  更多评论   


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理