views:

95

answers:

1

I'm currently having fun trying to learn some of the Boost libary. I'm currently doing what I guess will be a future homework project (semester hasn't started yet). However, this question is not about the homework problem, but about Boost.

Code:

/* AuctionApplication.h */
class AuctionApplication : boost::noncopyable
{
private:
    boost::ptr_vector<Auction> auctions_;
    boost::ptr_vector<Bidder>  bidders_;
    boost::ptr_vector<Bid>     bids_;


/* AuctionApplication.cpp */
Bid *AuctionApplication::GetLatestBid(const Auction *auction)
{
    Bid *highestBid = 0;

    BOOST_FOREACH(Bid *bid, bids_) // Error here!
        if (bid->GetAuction()->GetName() == auction->GetName())
            highestBid = bid;

BOOST_FOREACH use to work with normal vectors with the exact same code as above. Since I've started using ptr_vectors I get the error:

error C2440: '=' : cannot convert from 'Bid' to 'Bid *'

Leading me to believe that ptr_vector somehow obscures the pointer from the foreach method.

If I instead write

BOOST_FOREACH(Bid *bid, bids_)

I get four errors of the type

error C2819: type 'Bid' does not have an overloaded member 'operator ->'

which sucks, because I know bid is a pointer.

How can I make BOOST_FOREACH iterate properly over the ptr_vectors?

+5  A: 

ptr_vector takes ownership of heap allocated objects and presents each object as a reference so you don't need dereferencing and you use . instead of -> to access member variables/functions. e.g.

Bid highestBid = 0;
BOOST_FOREACH (Bid& bid, bids_)
    if (bid.GetAuction()->GetName() == auction->GetName())
        highestBid = &bid;
Ferruccio
As pointed out in the accepted answer to [this question](http://stackoverflow.com/questions/461507/), this can be avoided by using `value_type` when iterating over containers.
Space_C0wb0y
@Space_C0wb0y: I usually prefer to use `reference` or `const_reference` to `value_type`, no sense in copying.
Matthieu M.