重载地图的“<<”运算符

overload the "<<" operator for map

我被 C++ 中的一些代码卡住了。我无法重载 << 运算符来打印我的地图。

我试图让运算符超载,但没有成功。我不能在 C++98 中使用基于范围的 for 循环。

ostream & operator <<(std::ostream &os, 
                           const std::map<int, Person> &m)
{
    for (int i = 0; i < 3; i++)
    {
        os << i << ":";
        for (int x = 0; x < 2; i++) os << x << ' ';
        os << std::endl;
    }

    return os;
}

我现在的代码,没有超载 class:

class Person{
    public: 
    int kontostand; 
    string email;
    int alter;

    Person(int kontostand_, string email_, int alter_)
    {
        kontostand=kontostand_;
        email = email_;
        alter = alter_;
    }
};

int main()
{
    map<int, Person> testmap; 
    Person Kunde(100, "test", 21);
    Person Kunde2(200, "test", 22);
    Person Kunde3(300, "test", 23);

    testmap.insert(pair<int, Person>(1, Kunde));
    testmap.insert(pair<int, Person>(2, Kunde2));
    testmap.insert(pair<int, Person>(3, Kunde3));

    cout << testmap; 

    return 0;
}

有人知道如何打印我的地图吗?

template<typename Key, typename Value>
std::ostream& operator<<(std::ostream& out, const std::pair<Key, Value>& pair)
{
    return out << pair.first << ':' << pair.second;
}

template<typename Key, typename Value>
std::ostream& operator<<(std::ostream& out, const std::map<Key, Value>& c)
{
    typedef typename std::map<Key, Value>::const_iterator Iter;
    if (c.size() == 0) {
        return out << "<empty>";
    }
    Iter it = c.begin();
    out << *it;
    for(++it; it != c.end(); ++it) {
        out << ',' << *it;
    }
    return out;
}

Live example

首先你上面的代码有错误。

for (int x = 0; x < 2; i++) os << x << ' ';

应该是x++而不是i++

我相信您想重载运算符以便打印地图的输出。为了使运算符 << 接受 Complex 类型,您还必须在 Complex 类型中重载运算符。

请参考以下代码:

class Person {
public:
    int kontostand;
    string email;
    int alter;

    Person(int kontostand_, string email_, int alter_)
    {
        kontostand = kontostand_;
        email = email_;
        alter = alter_;
    }
    friend ostream& operator<<(std::ostream& os, const Person &p) {
        os << p.kontostand << "," << p.alter << "," << p.email;
        return os;
    }
};

ostream & operator <<(std::ostream &os,const std::map<int, Person> &m)
{
    for (map<int,Person>::const_iterator i = m.begin(); i != m.end(); ++i)
    {
        os << i->first << ":" << i->second << endl;
    }

    //for (int i = 0; i < 3; i++)
    //{
    //  os << i << ":";
    //  for (int x = 0; x < 2; x++) os << x << ' ';
    //  os << std::endl;
    //}

    return os;
}


int main()
{
    map<int, Person> testmap;
    Person Kunde(100, "test", 21);
    Person Kunde2(200, "test", 22);
    Person Kunde3(300, "test", 23);

    testmap.insert(pair<int, Person>(1, Kunde));
    testmap.insert(pair<int, Person>(2, Kunde2));
    testmap.insert(pair<int, Person>(3, Kunde3));

    cout << testmap;
    cin.get();
    return 0;
}

输出如下:

1:100,21,test
2:200,22,test
3:300,23,test

希望对您有所帮助。