stl(五)------生成 A-Z, AA - ZZ , AAA, -- ZZZ AAAA -- AAAZ 等序列的字符

来源:互联网 发布:虎头软件是什么 编辑:程序博客网 时间:2024/06/04 23:30
/*The Z -> AA, ZZ -> AAA, ZZZ -> AAAA transitions had me stuck for a while 
(which seems to be a problem in the good Doctor's perl program), 
but the following C++ code seems to work.It uses the fairly common idiom for printing base N values by constructing 
the value from least to greatest significant digit in an array, 
and then reversing it for presentation (in this case, returing it as a string).*/Code:#include <iostream>#include <string>#include <vector>#include <algorithm>#include <iterator>std::stringconv(unsigned long val){    static const char digits[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";    std::vector<char> buf;    buf.push_back(digits[val % 26]);    val /= 26;    if (val) {        do {            --val;            buf.push_back(digits[val % 26]);            val /= 26;        } while (val);    }    // copy constructed value into string.    // by iterating through the buffer in reverse order, the    // resulting string will be in the correct order.    std::string s;    std::copy(buf.rbegin(), buf.rend(), std::back_inserter(s));    return s;}


0 0
原创粉丝点击