如何转换 std::string
到 std::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/