Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing vector iterator to a function c++

Can anyone explain to me why the following segment compiles but the commented line after doesn't?

struct tObj
{
    int data;
    int moreData;
}

...

void funcToCall (tObj *obj, int moreData)
{
    //Useful stuff here
}

void mainFunction ()
{
    vector<tObj>::iterator it = vectorOfObjects.begin(); //assumes vectorOfObjects is already defined
    while (it != vectorOfObjects.end())
    {
        funcToCall (&(*it), 0); //This line works
        funcToCall (it, 0); //This line produces an error
        it++;
    }
}

The error produced is this:

error: cannot convert ‘std::vector<tObj>::iterator {aka __gnu_cxx::__normal_iterator<tObj*, std::vector<tObj> >}’ to ‘tObj*’

Any ideas on why &(*it) works but just plain it doesn't? Logically they are the same, aren't they?

Because doesn't * mean to dereference and & mean pass by reference aka cancelling each other out?

like image 823
Tim Avatar asked Oct 07 '14 07:10

Tim


People also ask

Can you pass an iterator by reference?

You could pass a const reference, but usually iterators are small enough that it gives no advantage over passing by value.

How do you pass an array of vectors to a function?

To pass an element of an array to a function, use the subscripted name of the array element as an argument in the function call. In Chapter 6, we showed how to pass scalars (i.e., individual variables and array elements) by reference with references. In Chapter 8, we show how to pass scalars by reference with pointers.


2 Answers

it is an iterator object, passing it as-is would mean you're trying to pass an object of type vector<tObj>::iterator for a function expecting tObj*, and thus the error.

When you do *it you'd get the underlying object the iterator is representing and when you apply & atop that, you get that object's address, which is of type tObj* which agrees with the function's argument type and thus no error.

like image 125
legends2k Avatar answered Sep 29 '22 17:09

legends2k


That the code would be compiled you have to declare an overloaded function like

void funcToCall ( std::vector<tObj>::iterator it, int moreData)
{
    //Useful stuff here
}

In general case types tObj * and vector<tObj>::iterator are different types though in some old realizations of std::vector its iterator is indeed defined as a pointer..

like image 26
Vlad from Moscow Avatar answered Sep 29 '22 17:09

Vlad from Moscow