I am trying to use a list as part of a struct due to the fact our products come in several colors. Is this some thing I can do or should i just use an array? Either way i have not found any examples on the web.
#include "stdafx.h"
#include<iostream>
#include<string>
#include<sstream>
#include<cctype>
#include<list>
using namespace std;
////////////////////////////////////////////////////////////////////////////////////////
// Constances
////////////////////////////////////////////////////////////////////////////////////////
#define N_PRODUCT 3
struct Brand_t {
int Model_Num;
string Product_Name;
list<string> Colors;
} brands [N_COLOR];
////////////////////////////////////////////////////////////////////////////////////////
// Functions
////////////////////////////////////////////////////////////////////////////////////////
int main()
{
string mystr;
int n;
for (n=0; n < N_PRODUCT; n++)
{
cout << "Enter Model Number: ";
std::getline (cin,mystr);
stringstream(mystr) >> brands[n].model_Num,4;
cout << "Enter Product Name: ";
getline(cin,classrooms[n].Product_Name);
list<string>::iterator it;
Students.push_back ("Red");
Students.push_back ("Yellow");
Students.push_back ("Blue");
}
return 0;
}
Yes, this can be done. Thanks to the RAII, the
listobject will be automatically initialized and freed based on the lifetime of your struct. Take note that even thought this is not the case in other programming languages such as Object Pascal, thestructandclassare effectively the same thing in C++, the only difference being default visibility of member methods and variables, as other answers have noted.You can not put non-PODS objects into unions though.
I suggest you use a
std::vectoror astd::arrayinstead of a C-style array. Astd::vectorwould probably be most useful if your array is supposed to be of dynamic size. If you use plainnewor evenmalloc(), then your objects will NOT be automatically freed (not even initialized withmalloc())