Medical physicist
Medical physicist

Reputation: 2594

Cast a vector and write it in a C++ stringstream

In the toy program below, I write and read a vector of doubles with a stringstream. However, how can I write v as a vector of (rounded) uint in ss, so that when w is read the output of the program is 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;
}

Upvotes: 0

Views: 388

Answers (2)

john
john

Reputation: 87932

This code reads the vector, rounds the values, and writes them out one at a time. The reverse when reading back from the stream.

#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;
}

Seems very straightforward, not sure what else you might have been expecting.

Note that converting a double to a uint64_t may overflow.

Upvotes: 1

Yunnosch
Yunnosch

Reputation: 26753

Assuming you want to "round" as in "round up from x.5" you can use

std::cout<<(unsigned int)(w.at(2)+0.5)<<std::endl;

It uses the offset of 0.5 to shift the truncation and results in rounding up as desired.

The output (of using this line in your shown program) is

3

Upvotes: 0

Related Questions