Click here to Skip to main content
15,904,935 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,
I have created below structure

typedef struct SSItems
   {
       string item;
       string parent;
   }ssitems;

And i want to increment size of structure array.

For example :
ssitems[0].item = "Item1";
                 sssitems[1].item = "Item2"........
                 ssitems[n].item = "Item3"

n is incremented at run time.
what is the solution?
Posted
Updated 26-Jul-11 2:32am
v2
Comments
Maximilien 26-Jul-11 8:51am    
Use a STL vector. I'm too buzy to write a whole solution this morning, but that should give you a good start.

As Maximilien said you should use the STL containers

http://www.cplusplus.com/reference/stl/vector/[^]

This site is a good reference for the STL containers.

but the basic mechanics are as follows,
1. Create the vector of structures.
2. push_back or insert what you want to store can be repeated vector will grow over time.
3. erase elements you don't need

hope this helps you.

remember to delete the container after you finish using it.
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 27-Jul-11 3:02am    
Good explanation and link, my 5.
--SA
Your code will not work as you have only defined your structure (ssitems is a type), you have not created an object of it. Also, you cannot dynamically increase C++ arrays; as others have suggested, use one of the STL containers.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 27-Jul-11 3:03am    
Good, my 5. ...wait a minute, how about realloc? So the array can be re-allocated to increase. In practice, bad idea anyway, STL is the right thing.
--SA
Stefan_Lang 27-Jul-11 3:23am    
I dunno, there are std::strings in that struct, it probably would work to realloc them, but it might depend on the implementation, so I'd say it's not guaranteed to work with realloc.

I know I do keep running into errors where colleagues in an effort to 'objectize' our legacy application replace char* attributes with std::string but forget to replace the memset() commands used to initialize the structs they're defined in! x(
Use something like

C++
struct SSItem
{
    string item;
    string parent;
};

class SSItems: public vecotr<SSItem>
{
public:
   SSItem& operator[](size_t n)
   {
      if(n>=size())  resize(n+1);
      return vector<SSItem>::operator[](n);
   }

   //required since the base one doesn't check boundaries
   const SSItem& operator[](size:t n) const
   {
      if(n>=size())  throw runtime_error("out of bound");
      return vector<SSItem>::operator[](n);
   }
};

SSitemms ssitems;


the [] operator will never go "out of range".
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900