Hi Guys,
Can anyone let me know how to iterate over the data from the
class MainProduct //This contains the main product which can be bought with //addon products.
{
public :
int productID;
char productName[50];
vector<Addon> ListAddon;
};
class Addon //These are the addon products (1-many relationship with Main //product
{
public:
int addonID;
char addonName[50];
};
class ListProduct //Create list of all the products which are purchased along //with addons
{
public:
vector<MainProduct> ListMainProduct;
};
ListAllProd.ListMainProduct.push_back(MainProd2);
//Iterator2 End
return 0;
}
This code is working perfectly but i want to iterate over these Main product and Addons to display in console. I can see the desired result while debugging.
for(int i = 0 ; i<ListAllProd.ListMainProduct.size();++i)
{
//We get information about Main Product.
std::cout<<ListAllProd.ListMainProduct[i].productID;
for(int j=0 ; j<ListAllProd.ListMainProduct[i].ListAddon.size();++j)
{
std::cout<<ListAllProd.ListMainProduct[i].ListAddon[j].addonID;
std::cout<<ListAllProd.ListMainProduct[i].ListAddon[j].addonName;
//We get information about Addon.
Your method works, but I've often heard people say it's not as safe as using an iterator.
This is how you would do it with iterators
1 2 3 4 5 6 7 8 9 10 11 12 13
vector<MainProduct>::iterator it1; // Making an iterator called it1
vector<Addon>::iterator it2;
for (it1 = ListAllProd.ListMainProduct.begin(); it1 < ListAllProd.ListMainProduct.end(); ++it1)
{// it1 cycles through all of the ListMainProducts in ListAllProd
cout << it1->productID; // We access elements of ListAllProd.ListMainProducts with ->
for(it2 = it1->ListAddon.begin(); it2 < it1->ListAddon.end(); ++it2)
{ // it2 will now iterate through all of the ListAddon objects.
cout << it2->addonID;
cout << it2->addonName;
}
cout << endl;
}