user2229408
user2229408

Reputation: 1

how to print using iterator in c++?

I am writing a program in VC++. Here I am declaring class Product and Client.In client I'm using a function list initProduct() in which list::iterator i; is used.I'm unable to display list using iterator. This my code:

#include "StdAfx.h"
#include <iostream>
#include <string>
#include <list>
#include <iterator>
using namespace std;
class Product
{
    int item_code;
    string name;
    float price;
    int count;
        public:
    void get_detail()
    {
        cout<<"Enter the details(code,name,price,count)\n"<<endl;
        cin>>item_code>>name>>price>>count;
    }

};

class Client
{
public:

    list<Product> initProduct()
    {
        char ans='y';
        list<Product>l;
        list<Product>::iterator i;
        while(ans=='y')
        {
            Product *p = new Product();
            p->get_detail();
            l.push_back(*p);
            cout<<"wanna continue(y/n)"<<endl;
            cin>>ans;
        }
        cout<<"*******"<<endl;

        for(i=l.begin(); i!=l.end(); i++)
             cout << *i << ' ';    //ERROR no operator << match these operand
        return l;
    }
};
int main()
{
    Client c;
    c.initProduct();
    system("PAUSE");
}

Upvotes: 0

Views: 286

Answers (3)

rwols
rwols

Reputation: 3078

You must implement the following function

class Product {
// ...
    friend std::ostream& operator << (std::ostream& output, const Product& product)
    {
        // Just an example of what you can output
        output << product.item_code << ' ' << product.name << ' ';
        output << product.price << ' ' << product.count;
        return output;
    }
// ...
};

You declare the function a friend of the class because it must be able to access the private properties of a Product.

Upvotes: 3

Thomas Ayoub
Thomas Ayoub

Reputation: 29431

If you're using C++11 you can use auto :

for(auto it : Product)
    {
        cout << it.toString();
    }

but you'll have to implement this toString() which will display all the infos you want

Upvotes: 0

Mats Petersson
Mats Petersson

Reputation: 129314

You need to produce an ostream& operator<<(ostream& os, const Product& product) that prints the information you want to display.

Upvotes: 2

Related Questions