简体   繁体   中英

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?

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.

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..

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