当前位置: 首页 > 工具软件 > zz-doctor > 使用案例 >

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

谷梁晟
2023-12-01
/*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::string
conv(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;
}


 类似资料: