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

时间:2019-06-11 15:30:04

标签: c++ c++98

我陷入了C ++的某些代码中。我无法重载<<运算符以打印我的地图。

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

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

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

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:2)

首先,上面的代码有误。

  

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

我希望这会有所帮助。