Home > Back-end >  How can I convert a std::string to std::vector?
How can I convert a std::string to std::vector?

Time:12-02

I have some code which I need to serialize a vector into bytes, then send it to a server. Later on, the the server replies with bytes and I need to serialize it back into a vector.

I have managed to serialize into bytes okay, but converting back into a vector is getting the wrong values:

#include <iostream>
#include <string>
#include <vector>


int main()
{
    std::vector<double> v = {1, 2, 3};
    std::cout << "Original vector: " << std::endl;
    for (auto i : v) {
        std::cout << i << " ";
    }
    std::cout << std::endl;

    std::string str((char *)v.data(), sizeof(v[0])*v.size());
    std::cout << "Vector memory as string: " << std::endl << str << std::endl;

    std::cout << "Convert the string back to vector: " << std::endl;
    auto rV = std::vector<double>(&str[0], &str[str.size()]);
    for (auto i : rV){
        std::cout << i << " ";
    }
    std::cout << std::endl;

    return 0;
}

This outputs:

Original vector: 
1 2 3 
Vector memory as string: 
�?@@
Convert the string back to vector: 
0 0 0 0 0 0 -16 63 0 0 0 0 0 0 0 64 0 0 0 0 0 0 8 64 

What is going wrong with my conversion from a string to a vector, and how can I fix it?

Here is a link to run the code.

CodePudding user response:

Like this

std::vector<double>((double*)str.data(), (double*)(str.data()   str.size()));

Basically the same as your code, but I've added some casts. In your version the chars get converted directly into doubles (as if you had written rV[0] = str[0] etc) and the vector is sizeof(double) times too big.

  • Related