c++ - 转换向量并将其写入 C++ 字符串流
问题描述
在下面的玩具程序中,我使用stringstream编写和读取双精度向量。但是,如何在ss中将v写为(四舍五入)uint 的向量,以便在读取w时程序的输出为 3?
#include <sstream>
#include <vector>
#include <iostream>
int main() {
std::vector<double> v = {0.1, 1.2, 2.6};
std::vector<double> w;
std::stringstream ss;
ss.write(const_cast<char*>(reinterpret_cast<const char*>(&v.at(0))), v.size() * sizeof(v.at(0))); // Here it should cast v first into uint an then into char
for(int i = 0; i < v.size(); ++i) {
double val; // It should be uint val
ss.read(reinterpret_cast<char*>(&val), sizeof(val));
w.push_back(val);
};
std::cout<<w.at(2)<<std::endl;
return 0;
}
解决方案
此代码读取向量,对值进行四舍五入,然后一次写出一个。从流中读回时相反。
#include <sstream>
#include <vector>
#include <iostream>
#include <cstdint>
#include <cmath>
int main() {
std::vector<double> v = {0.1, 1.2, 2.6};
std::vector<double> w;
std::stringstream ss;
for(int i = 0; i < v.size(); ++i) {
uint64_t val = static_cast<uint64_t>(std::round(v.at(i)));
ss.write(const_cast<char*>(reinterpret_cast<const char*>(&val)), sizeof(val));
}
for(int i = 0; i < v.size(); ++i) {
uint64_t val;
ss.read(reinterpret_cast<char*>(&val), sizeof(val));
w.push_back(static_cast<double>(val));
};
std::cout<<w.at(2)<<std::endl;
return 0;
}
看起来很简单,不知道你还期待什么。
请注意,将 a 转换double
为 auint64_t
可能会溢出。
推荐阅读
- javascript - 我怎样才能从这个数组中删除 68?
- java - 为什么在更改组的比例后更改 JavaFX 组中一个形状的翻译属性会影响其他形状
- jenkins - 来自分支和特定提交的 Jenkins 管道脚本不起作用
- python - 如何屏蔽用户密码输入并将其保存为输出以替换另一个文件中的默认密码
- javascript - MongoDB $pull 在具有多个匹配项的深度嵌套数组上
- python - 在选择器输出中保留“转义”之类的字符
- python - Chrome 驱动程序在不受支持的非 bmp 字符上崩溃。如何绕过这个
- symfony - PhpStorm Symfony 问题(没有找到任何东西)
- python - 如何使用 Python 将简体中文字符转换为 html 转义字符?
- python - 使用熊猫数据框,如何按多列分组并添加新列