简体   繁体   English

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

[英]How to convert std::string to std::vector<std::byte> in C++17?

How do I convert a std::string to a std::vector<std::byte> in C++17? 如何在C ++ 17中将std::string转换为std::vector<std::byte> Edited: I am filling an asynchronous buffer due to retrieving data as much as possible. 编辑:由于要尽可能多地检索数据,所以我正在填充异步缓冲区。 So, I am using std::vector<std::byte> on my buffer and I want to convert string to fill it. 因此,我在缓冲区上使用了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());

but I am getting this error: 但我收到此错误:

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

Using std::transform should work: 使用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;
}

Output: 输出:

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

std::byte is not supposed to be a general purpose 8-bit integer, it is only supposed to represent a blob of raw binary data. std::byte不应该是通用的8位整数,而只能代表原始二进制数据的blob。 Therefore, it does (rightly) not support assignment from char . 因此,它(正确地)不支持char赋值。

You could use a std::vector<char> instead - but that's basically what std::string is. 您可以改用std::vector<char> -但这基本上就是std::string


If you really want to convert your string to a vector of std::byte instances, consider using std::transform or a range- for loop to perform the conversion. 如果您确实要将字符串转换为std::byte实例的向量,请考虑使用std::transform或range- for循环执行转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM