Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing an object pointed to by an iterator by reference to a function C++

I though that I understood iterators and addressing etc. but obviously not. See my below code below which is purely an example.

I need to be able to pass by pointer or reference each structure of mystructs to MyFunc(). The function should be able to update the actual structure that is passed, and not by copy or value.

I receive the compiler error :

error: cannot convert 'MY_STRUCT' to 'MY_STRUCT*' for argument '1' to 'void MyFunc(MY_STRUCT*)'

If I just pass the iterator address, this also doesn't work.

What is the correct way to do this. Thanks in advance.

typedef struct
{
   int var1;
   int var2;
   std::string name;

}MY_STRUCT;

std::list<MY_STRUCT> mystructs;

void MyFunc(MY_STRUCT*)
{
    // Do something
}


// populate the list with structs etc.. not included here
//.....


for (std::list<MY_STRUCT>::iterator it = mystructs.begin();it != mystructs.end(); ++it)
{
     MyFunc(*it);
}
like image 679
Engineer999 Avatar asked Oct 15 '25 07:10

Engineer999


1 Answers

Passing by reference in C++ is done with:

void MyFunc(MY_STRUCT&)
{
    // Do something
}

So your call would be correct, what you currently want is to pass the pointer, which you can do with dereferencing the dereferenced iterator (by passing the address of the dereferenced object):

void MyFunc(MY_STRUCT*)
{
    // Do something
}


// populate the list with structs etc.. not included here
//.....
int main() {

    for (std::list<MY_STRUCT>::iterator it = mystructs.begin();it != mystructs.begin(); ++it)
    {
         MyFunc(&*it);
    }
}
like image 55
RoQuOTriX Avatar answered Oct 16 '25 22:10

RoQuOTriX