tzippy
tzippy

Reputation: 6648

Copy vector of type 'bar to vector of type BYTE

I have a member vector std::vector<BYTE> memberVec

In an internal member function I have an std::vector of structs of type bar which contain four double values each. I need to copy the content fo std::vector byte by byte into std::vector<BYTE> foo.

This is what I do now, and I would really appreciate it, if you show me a more C++ style approach:

    typedef struct{
        double dX1, dY1, dX2, dY2;
    }bar;

        std::vector<bar> oBar;
        //fill  obar
        memberVec.resize(oBar.size()*sizeof(double) * 4);
        BYTE* pData = (BYTE*)&memberVec[i];
        for (int i = 0; i < oBar.size(); i++)
        {
            memcpy(pData, &oBar[i].dX1, sizeof(double));
            pData += sizeof(double);
            memcpy(pData, &oBar[i].dY1, sizeof(double));
            pData += sizeof(double);
            memcpy(pData, &oBar[i].dX2, sizeof(double));
            pData += sizeof(double);
            memcpy(pData, &oBar[i].dY2, sizeof(double));
            pData += sizeof(double);

        }

Upvotes: 1

Views: 90

Answers (1)

Drax
Drax

Reputation: 13298

Just do:

memberVec.assign(reinterpret_cast<const char*>(oBar.data()),
                 reinterpret_cast<const char*>(oBar.data() + oBar.size()));

Upvotes: 2

Related Questions