简体   繁体   中英

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

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 .

您需要产生一个ostream& operator<<(ostream& os, const Product& product) ,以打印出您想要显示的信息。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM