Iterate through a list of objects and point to the node that matches a certain criteria

I am using a custom data structure 'block' and have stored several blocks in a list:

 list openList<block>

I now need to iterate through each block, access the data member 'f' (an integer) and check which has the lowest f cost.

My logic would be to simply have a pointer pointing to the best block value, rather than each time copying the best blocks values.

Here's my code:

for (std::list<block>::iterator openi = openList.begin(); openi != openList.end();  openi++){
        if ((*openi).f < bestFCost){
            bestFCost = (*openi).f;
            // Here's where I need help....
        }
    }

I don't think what I'm asking of the iterator is possible. I wish to set

 block * Q 

To the data the iterator points to, but I need the entire object not the data members.

Edit: Very simple solution! I initilised Q with a typo (Q* instead of *Q)!

block * Q = 0;

Then in the part of the loop I commented:

 Q = &(*openi)

:)

Upvotes: 0

Views: 124

Answers (1)

Bernhard Barker
Bernhard Barker

Reputation: 55599

*openi is of type block, right? So you can simply take the address of that:

block * Q = &*openi;

The &* might seem redundant, but the * is an operator on the iterator, returning a block type, as opposed to scenario's where * is a dereference, and the & references it again.

Or you can store the iterator itself:

std::list<block>::iterator Q = openi;

Or you can store the object by value, assuming you implemented the copy constructor:

block Q = *openi;

Upvotes: 1

Related Questions