(注意:答案适用于标准 C++;可能需要对范围迭代进行少量修改才能在较旧的方言中工作。我认为这些对算法效率的核心问题无关紧要,而该核心问题对问题很重要.)
您可以通过意识到您基本上提前知道答案并且不需要做所有这些动态工作,从而为自己节省大量工作。
std::string uint8_vector_to_hex_string(const vector<uint8_t>& v)
{
std::string result;
result.reserve(v.size() * 2); // two digits per character
static constexpr char hex[] = "0123456789ABCDEF";
for (uint8_t c : v)
{
result.push_back(hex[c / 16]);
result.push_back(hex[c % 16]);
}
return result;
}
本着“识别算法”的精神,这里有一个用于数字序列的位值格式化的分离算法。首先是用例:
#include <iostream>
#include <string>
#include <vector>
// bring your own alphabet
constexpr char Alphabet[] = "0123456789ABCDEF";
// input
std::vector<unsigned char> const v { 31, 214, 63, 9 };
// output (Note: *our* responsibility to make allocations efficient)
std::string out;
out.reserve(v.size() * 2);
// the algorithm
place_value_format<char, // output type
2, // fixed output width
16>( // place-value number base
v.begin(), v.end(), // input range
std::back_inserter(out), // output iterator
Alphabet); // digit representation
现在算法:
#include <algorithm>
#include <iterator>
template <typename Out, std::size_t NDigits, std::size_t Base,
typename InItr, typename OutItr>
OutItr place_value_format(InItr first, InItr last, OutItr out, Out const * digits)
{
for (; first != last; ++first)
{
Out unit[NDigits];
auto val = *first;
for (auto it = std::rbegin(unit); it != std::rend(unit); ++it)
{
*it = digits[val % Base];
val /= Base;
}
out = std::copy(std::begin(unit), std::end(unit), out);
}
return out;
}