如何在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)
使用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)
| 归档时间: |
|
| 查看次数: |
827 次 |
| 最近记录: |