Re: structures and pointers by John
John
Wed Sep 27 00:13:42 CDT 2006
"www.fruitfruit.com" <no_email@fruitfruit.com> wrote in message
news:Onf1rte4GHA.1252@TK2MSFTNGP04.phx.gbl
> nemesia31@gmail.com wrote:
>> i have a structure
>> typedef struct tm
>> {
>> int date;
>> int hour;
>> int minutes;
>> } time;
>>
>> i want to use this structure dynamically, ie, i want it to grow.
>>
>> like it would be
>> time *sept= new time;
>> sept->date=15;
>> .....
>> ........
>> ......
>> but i want something like
>>
>> for(int i=0;i<MAX;i++)
>> {
>> sept[i]->date=i+5;
>> }
>>
>> i want to grow the structure dynamically, ie, the valur of MAX is
>> provided at runtime.
>> how can i do tht????
>>
>
> Use STL container
> #include <deque>
> std::deque<*time> time_collection;
> for(int i=0; i< MAX; i++)
> {
> time_collection.push_back( new time );
> time_collection[i]->date = i+5;
> }
Your collection isn't buying you anything here since you will still need to
manually delete the memory allocated. You could achieve the same effect
with:
#include <iostream>
using namespace std;
struct Time
{
int date;
int hour;
int minutes;
};
int main()
{
int MAX;
cin >> MAX;
Time *sept= new Time[MAX];
for(int i=0;i<MAX;i++)
{
sept[i].date=i+5;
}
// later
delete [] sept;
return 0;
}
Alternatively, you could use a container to avoid manual memory allocation.
#include <iostream>
#include <vector>
using namespace std;
struct Time
{
int date;
int hour;
int minutes;
};
int main()
{
int MAX;
cin >> MAX;
vector<Time> sept(MAX, Time());
for(int i=0;i<MAX;i++)
{
sept[i].date=i+5;
}
// no delete required
return 0;
}
If the size of MAX may change during the running of the program, then the
member functions resize() or, as you indicated, push_back() may be used.
--
John Carson