Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to memcpy iterator element in C++?

I have the following code in C++:

typedef struct 
{
   int age;
   int roomNumber;
} Student;

Student student;
student.age = 20;
student.roomNumber = 10;

vector<Student> studentV;
student.push_back(student);
student.push_back(student);
student.push_back(student);

Student student1[3];

int i;

for(vector<Student>::const_iterator iterator = studentV.begin();
    iterator != studentV.end(); ++iterator,++i)
{
   memcpy(&student1[i], iterator, sizeof(Student));
}

It show the following message for the memcpy part:

error: cannot convert 'std::vector<Student>::const_iterator {aka __gnu_cxx::__normal_iterator<const Student*, std::vector<Student> >}' to 'const void*' for argument '2' to 'void* memcpy(void*, const void*, size_t)'

What is the problem and how to fix it? is iterator can not be copied like this?

like image 827
ratzip Avatar asked Oct 15 '25 08:10

ratzip


2 Answers

The second argument of memcpy should be address of Student object, so you should use &*iterator instead of iterator. Because of operator overloading those two are not equivalent. But I would recommend not to use memcpy at all.

like image 154
Wojtek Surowka Avatar answered Oct 16 '25 21:10

Wojtek Surowka


What you want to do is copy what the iterator refers to. Use *iterator to get the object referenced by the iterator and & to get its address. By the way DO NOT use memcpy but the copy constructor:

student1[i] = *iterator;
like image 23
neuro Avatar answered Oct 16 '25 22:10

neuro