Home > OS >  Function that copies a std::vector<POD> into std::vector<char*>?
Function that copies a std::vector<POD> into std::vector<char*>?

Time:10-20

I need a function that can take a vector of any one of float, int, double or short. It should then copy all the data in that vector into a new vector of char*.

Here my attempt. This is the first time I ever had to use memcpy so I don't know what I am doing.

#include <vector>
#include <memory>


std::vector<float> vertices = { 0.0, 0.1, 0.2, 0.3, 0.4 };

std::unique_ptr<std::vector<char*>> buffer = std::make_unique<std::vector<char*>>();
template<class Type>
void SetVertices(const std::vector<Type>& v)
{
    buffer->clear();
    buffer->resize(v.size() * sizeof(Type));
    memcpy(buffer.get(), v, v.size() * sizeof(Type));
}

int main()
{
    SetVertices(vertices);
} 

Here is the error message:

error C2664: 'void *memcpy(void *,const void *,size_t)': cannot convert argument 2 from 'const std::vector<float,std::allocator>' to 'const void *'

CodePudding user response:

There are a couple issue with your code. First is that memcpy takes a pointer to the data you want copied and to the location you want the data copied to. That means you can't pass v to memcpy but need to pass v.data() so you get a pointer to the elements of the vector.

The second issue is that buffer has the wrong type. You want to store your data as bytes, so you want to store it in a char buffer. A std::vector<char*> is not a byte buffer but a collection of pointers to potential buffers. What you want is a std::vector<char> which is a single byte buffer. Making those changes gives you

#include <vector>
#include <memory>
#include <cstring>

std::vector<float> vertices = { 0.0, 0.1, 0.2, 0.3, 0.4 };

std::vector<char> buffer;
template<class Type>
void SetVertices(const std::vector<Type>& v)
{
    buffer.clear();
    buffer.resize(v.size() * sizeof(Type));
    std::memcpy(buffer.data(), v.data(), v.size() * sizeof(Type));
}

int main()
{
    SetVertices(vertices);
} 

Live example

  •  Tags:  
  • c
  • Related