Search code examples
c++vectorprintingstd-pair

How to print a vector of pairs that have as first and second 2 classes in c++?


I have something like this where Client and Order are classes :

  std::vector<std::pair<Client,Order>> pair;
    pair.push_back(std::make_pair(Client(2,"Anca"),Order(3,1)));
    pair.push_back(std::make_pair(Client(16,"Maria"),Order(1,3)));
    pair.push_back(std::make_pair(Client(29,"Alex"),Order(10,5)));
class Client{
private:
    int dateWhenOrderWasPlaced;
    std::string clientName;
public:
    Client(int date,std::string name){
        dateWhenOrderWasPlaced=date;
        clientName=name;
    }
class Order{
private:
    int amountPizza;
    int pizzaAge;
public:
    Order(int amPizza,int agePizza){
        amountPizza=amPizza;
        pizzaAge=agePizza;
    }

And i can't figure out how to print this.I have tried in many ways :

void print(std::vector<std::pair<Client,Order>> pair){
    for(const auto& it : pair){
        std::cout << "First: "<<pair[it].first<< ", Second: " << pair[it].second <<std::endl;
    }
}

And this :

void print(std::vector<std::pair<Client,Order>> pair){
    for(const auto& it : pair){
        std::cout << "First: "<<it.first<< ", Second: " << it.second <<std::endl;
    }
}

And in the both ways i have error(first-no operator[] and second,no operator <<)


Solution

  • Your first attempt does not work because it is the actual pair but std::pair does not have an operator[]. Your second attempt is the correct way to go, but it does not work because you have not defined operator<< for your classes.

    So, simply define operator<<, eg:

    class Client
    {
    private:
        int dateWhenOrderWasPlaced;
        std::string clientName;
    
    public:
        Client(int date, std::string name)
            : dateWhenOrderWasPlaced(date), clientName(name)
        {
        }
    
        friend std::ostream& operator<<(std::ostream &os, const Client &c)
        {
            // print c.dateWhenOrderWasPlaced and c.clientName to os as needed...
            return os;
        }
    };
    
    class Order
    {
    private:
        int amountPizza;
        int pizzaAge;
    
    public:
        Order(int amPizza, int agePizza)
            : amountPizza(amPizza), pizzaAge(agePizza)
        {
        }
    
        friend std::ostream& operator<<(std::ostream &os, const Order &o)
        {
            // print o.amountPizza and o.pizzaAge to os as needed...
            return os;
        }
    };
    
    void print(const std::vector<std::pair<Client,Order>> &pair)
    {
        for(const auto& it : pair)
        {
            std::cout << "First: " << it.first << ", Second: " << it.second << std::endl;
        }
    }