简体   繁体   中英

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;
}
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;
}

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