Search code examples
c++pointersdereference

Dereferencing vector pointers with a range based for loop


This is the code from my main() function:

std::map<int, std::string> candyMap;
std::vector<House*> houseVector;
std::ifstream abodeFile{houseFile};
std::string houseLine;
if(abodeFile.is_open())
{
    while(getline(abodeFile, houseLine))
    {
        houseVector.push_back(new House(houseLine, candyMap));
    }
}

std::cout << std::setw(11) << " ";
for(auto i:houseVector)
{
    std::cout << std::setw(11) << i;
} 

I am trying to print out the elements from houseVector. Obviously, with the above code I get the addresses of the elements. When I do *i, I get an operator error with <<. What is the correct way to dereference here?


Solution

  • you need to overload ostream << operator, e.g.:

    class House
    {
        int member;
    public:
        explicit House (int i) : member(i) {}
        friend ostream& operator<<(ostream& os, const House& house);
    };
    
    ostream& operator<<(ostream& os, const House& house)
    {
        os <<house.member << '\n';
        return os;
    }
    

    Live on Godbolt


    Or without friend:

    class House
    {
        int member;
    public:
        explicit House (int i) : member(i) {}
    
        std::ostream &write(std::ostream &os) const { 
            os<<member<<'\n';
            return os;
        }
    };
    
    std::ostream &operator<<(std::ostream &os, const House& house) { 
         return house.write(os);
    }
    

    Live on Godbolt