首页 > 解决方案 > 转换向量并将其写入 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;
}

标签: c++stringstream

解决方案


此代码读取向量,对值进行四舍五入,然后一次写出一个。从流中读回时相反。

#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可能会溢出。


推荐阅读