c++ - 如何有效地格式化从 std::vector 到 std::string 的值?

标签 c++ stdvector stringstream

我有一个程序需要 std::vector<uint8_t>并返回 std::string格式为十六进制字符后跟 ASCII 文本,如下所示:

03 00 00 54 00 00 00 08 00 00 00 00 00 00 00 00 ASCII ...T......

74 21 B8 30 00 2C 2E 31 62 30 74 21 A8 30 00 2C ASCII t!.0.,.1b0t!.0.,

这是代码的主要部分:

std::vector<uint8_t> value;
std::stringstream printed_line;
std::stringstream tempHexLine;
std::stringstream tempAsciiLine;

for (size_t printed_bytes = 0; printed_bytes < value.size(); printed_bytes += bytes_line) {

    for (int i = 0; i < bytes_line; ++i) {
        tempHexLine << std::setfill('0') << std::setw(2) << std::uppercase << std::hex << static_cast<uint16_t>(value[printed_bytes + i]) << " ";
    }

    for (int i = 0; i < bytes_line; ++i) {

            if(isprint(value[printed_bytes + i])) {

                if (value[printed_bytes + i] == 60) {
                    tempAsciiLine << "&lt;";

                } else if(value[printed_bytes + i] == 62) {
                    tempAsciiLine << "&gt;";

                } else {
                    tempAsciiLine << static_cast<char>(value[printed_bytes + i]);
                }

            } else {
                tempAsciiLine << ".";
            }
        }
    }

    printed_line << tempHexLine.str() << "   " << tempAsciiLine .str();

我要解决的问题是,当 vector 大小很大(> 1000 个元素)时,这会花费很长时间 - 大约 70% 的样本使用 Very Sleepy 到 ::operator<<功能。

将这样的格式应用于 vector 中的值的最快方法是什么? vector 需要分解成明确定义的数据 block ,因此一次输出一个字节似乎是一种低效的方法。

最佳答案

这对于高效编写来说应该是微不足道的。试试这个:

#include <algorithm>
#include <cstdint>
#include <iterator>
#include <string>
#include <vector>

std::string to_hex(std::vector<uint8_t> const & v)
{
    std::string result;
    result.reserve(4 * v.size() + 6);

    for (uint8_t c : v)
    {
        static constexpr char alphabet[] = "0123456789ABCDEF";

        result.push_back(alphabet[c / 16]);
        result.push_back(alphabet[c % 16]);
        result.push_back(' ');
    }

    result.append("ASCII ", 6);
    std::copy(v.begin(), v.end(), std::back_inserter(result));

    return result;
}

关于c++ - 如何有效地格式化从 std::vector 到 std::string 的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27067072/

相关文章:

C++字符串流转换错误: segmentation fault

c++ - 检测何时在字符串流的末尾

c++ - 从 'QWidget*' 到 'QwtPlotCanvas*' [-fpermissive] 的无效转换

c++ - undefined reference yyparse C++

C++ OpenMP 和 std::vector<bool>

c++ - std::vector::erase() 删除错误的元素

c++ - Std::stringstream move 分配在 gcc 中不起作用

c++ - 请求 ''中的成员 '',非类类型

c++ - 退出 C++ 控制台程序

c++ - C++ 不将 `std::vector<std::string>` "overload"作为参数添加到 `main()` 的原因是什么?