结构数组的动态分配 [英] dynamic allocation of structure array

查看:88
本文介绍了结构数组的动态分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,
我创建了以下结构

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


而且我想增加结构数组的大小.

例如:

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


n在运行时递增.
解决方案是什么?

解决方案

正如Maximilien所说,您应该使用STL容器

http://www.cplusplus.com/reference/stl/vector/ [ 结构 SSItem { 字符串项目; 字符串父母 }; SSItems: public vecotr< SSItem> { 公共: SSItem& 运算符 []( size_t n) { 如果(n> = size())resize(n + 1); 返回 vector< SSItem> ::: 运算符 [](n); } // 是必需的,因为基类不检查边界 常量 SSItem& 运算符 [](大小:t n)常量 { 如果(n> = size())抛出 runtime_error( " ); 返回 vector< SSItem> ::: 运算符 [](n); } }; SSitemms ssitems;



[]运算符将永远不会超出范围".


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?

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.


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.


Use something like

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".


这篇关于结构数组的动态分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆