c++ - 如何在 C++17 中将 std::string 转换为 std::vector<std::byte>?

标签 c++ byte

如何转换 std::stringstd::vector<std::byte>在 C++17 中? 已编辑: 由于要尽可能多地检索数据,我正在填充一个异步缓冲区。所以,我正在使用 std::vector<std::byte>在我的缓冲区上,我想转换字符串以填充它。

std::string gpsValue;
gpsValue = "time[.........";
std::vector<std::byte> gpsValueArray(gpsValue.size() + 1);
std::copy(gpsValue.begin(), gpsValue.end(), gpsValueArray.begin());

但是我收到了这个错误:

error: cannot convert ‘char’ to ‘std::byte’ in assignment
        *__result = *__first;
        ~~~~~~~~~~^~~~~~~~~~

最佳答案

使用 std::transform应该工作:

#include <algorithm>
#include <cstddef>
#include <iostream>
#include <vector>

int main()
{
    std::string gpsValue;
    gpsValue = "time[.........";
    std::vector<std::byte> gpsValueArray(gpsValue.size() + 1);
    std::transform(gpsValue.begin(), gpsValue.end(), gpsValueArray.begin(),
                   [] (char c) { return std::byte(c); });
    for (std::byte b : gpsValueArray)
    {
        std::cout << int(b) << std::endl;
    }
    return 0;
}

输出:

116
105
109
101
91
46
46
46
46
46
46
46
46
46
0

关于c++ - 如何在 C++17 中将 std::string 转换为 std::vector<std::byte>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52699435/

相关文章:

c++ - 如果以后未使用/设置未初始化的数据,是否可以复制它?

c# - C# 中的 byte[] 究竟是什么?

java - 文本字符串 二进制字符串 字节数组 float 和返回 Java

c++ - 为什么打印的值都是垃圾?我们如何解决这个问题?

c++ - QVariant 中的 QList,QVariant::type() 返回奇怪的类型

c++ - gsoap linux c++/struct 传递失败

在C中将char数组转换为int

arrays - 在 PowerShell 中创建 Byte[]

C++ 如何将两个带符号的 8 位数字组合成一个 16 位短整数?无法解释的结果

c++ - 为什么创建 friend 类的实例会导致 "undefined reference to"错误?