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 list object 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, the struct and class are 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::vector or a std::array instead of a C-style array. A std::vector would probably be most useful if your array is supposed to be of dynamic size. If you use plain new or even malloc(), then your objects will NOT be automatically freed (not even initialized with malloc())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With