Man
Man

Reputation: 1

How would you go about dereference a vector iterator

I'm currently learning C++ and ran into a little problem. The code below prints the address on the vector, but how do I let it spill the contents behind the address?

std::vector<BasePayroll*> emps;
emps.push_back(&Jane);

for (std::vector<BasePayroll*>::iterator it = emps.begin(); it != emps.end(); it++ ) {
    std::cout << *it;
}

Upvotes: 0

Views: 90

Answers (1)

Ted Lyngmo
Ted Lyngmo

Reputation: 117258

std::vector<BasePayroll*> emps; // when you dereference the iterator once you get
                                // what you have stored in the vector, a BasePayroll*
emps.push_back(&Jane);

for (std::vector<BasePayroll*>::iterator it = emps.begin(); it != emps.end(); it++ ) {
    std::cout << *(*it);        // do double dereferencing to get a BasePayroll& instead
}

You could also let a range-based for loop do the first level of dereferencing:

for(BasePayroll* pbpr : emps) {
    std::cout << *pbpr;
}

For the obove to work you also need

std::ostream& operator<<(std::ostream& os, const BasePayroll& bpr) {
    // output BasePayroll-data using bpr
    return os;
}

Upvotes: 1

Related Questions