简体   繁体   English

如何在C ++中使用迭代器进行打印?

[英]how to print using iterator in c++?

I am writing a program in VC++. 我正在用VC ++编写程序。 Here I am declaring class Product and Client.In client I'm using a function list initProduct() in which list::iterator i; 在这里,我声明了Product和Client类。在客户端中,我使用的是一个函数列表initProduct(),其中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 . 您将该函数声明为该类的朋友,因为该函数必须能够访问Product的私有属性。

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

If you're using C++11 you can use auto : 如果您使用的是C++11 ,则可以使用auto

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

but you'll have to implement this toString() which will display all the infos you want 但您必须实现此toString() ,该toString()将显示您想要的所有信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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