|
-
February 10th, 2009, 12:13 AM
#1
Dynamic Array and Structures
#include <cstdlib>
#include <iostream>
#include <cstring>
using namespace std;
struct candyBar
{
string strCandyBarName;
double doubleWeightCandyBar;
int intNumberCalories;
};
int main(int argc, char *argv[])
{
candyBar * pSnack = new candyBar [3];
pSnack[0] = {"Mocha Munch", 2.3, 350}; // doesnt compile...
// looking for clean way to define a dynamic array using a structure
// without using pSnack[0].strCandyBarName -> "Munch";
// any help making it cleaner???
delete [] pSnack;
system("PAUSE");
return EXIT_SUCCESS;
}
-
February 10th, 2009, 12:35 AM
#2
Re: Dynamic Array and Structures
Code:
#include <string>
#include <vector>
struct candyBar
{
candyBar() : doubleWeightCandyBar(0), intNumberCalories(0)
{}
candyBar(const std::string& name, double weight, int calories)
: strCandyBarName(name)
, doubleWeightCandyBar(weight)
, intNumberCalories(calories)
{}
std::string strCandyBarName;
double doubleWeightCandyBar;
int intNumberCalories;
};
int main(int argc, char *argv[])
{
std::vector<candyBar> snacks;
snacks.push_back(candyBar("Mocha Munch", 2.3, 350));
}
No manual memory management, no new, no delete. It's all handled by stl library. When you use C++, use C++, it will make much easier.
Here and here are good start for vector. Rest is left as an exercise for the reader.
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|