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

Fel*_*ipe 3 c++ byte

如何在C ++ 17中将a转换std::string为a std::vector<std::byte>编辑:由于要尽可能多地检索数据,所以我正在填充异步缓冲区。所以,我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());
Run Code Online (Sandbox Code Playgroud)

但我收到此错误:

error: cannot convert ‘char’ to ‘std::byte’ in assignment
        *__result = *__first;
        ~~~~~~~~~~^~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)

jde*_*esa 5

使用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;
}
Run Code Online (Sandbox Code Playgroud)

输出:

116
105
109
101
91
46
46
46
46
46
46
46
46
46
0
Run Code Online (Sandbox Code Playgroud)