使用基于范围的 for 循环取消引用向量指针

Dereferencing vector pointers with a range based for loop

这是我的 main() 函数的代码:

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

我正在尝试打印出 houseVector 中的元素。显然,通过上面的代码我得到了元素的地址。当我执行 *i 时,出现 << 的运算符错误。在这里取消引用的正确方法是什么?

您需要重载 ostream << 运算符,例如:

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

生活在 Godbolt


或没有朋友:

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

生活在 Godbolt