简体   繁体   中英

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);

        }

Just do:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM