C++结构体动态数组

3

你能帮助我组织一个动态点数组吗?

我已经处理了一个动态整数数组,但是我不知道如何使用结构体来组织它。

这是我目前的代码...

#include "stdafx.h"
#include <cstdlib>;
#include <iostream>;
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
  int i = 0; // Array index.
  struct Point
  {
    int x;
    int y;
  };
  size_t n = sizeof(int);
  int * points = static_cast<int*>(malloc(n));
  char command;
  do
  {
    cout << "n - Create new point." << endl;
    cout << "q - Quit." << endl;
    cout << "Input a new command: ";
    cin >> command;
    if (command == 'n')
    {
      points[i] = 1;
      i++;
      /* points[i] = new Point();
         points[i].x = 1;
         points[i].y = 1; */
      // cout<<"("<<point1.x<<","<<point1.y<<")";               
    }               
    else if (command == 'q')
    {       
      for (int j = 0; j < i; j++)
        cout << points[j] <<endl;
      system("pause");
      return 0;
    }
    else
    {
      cout << "Please, enter a correct command." << endl << endl << endl;               
    }
  } while (true);
  system("pause");  
  return 0;
}

可能是在C++中使用动态数组的重复问题。 - R. Martinho Fernandes
不要强制转换malloc的结果,并且不要在函数内部声明结构体。 - Eregrith
4个回答

3

std::vector是一种封装动态大小数组的序列容器。

--cppreference.com

C++中,应该使用它而不是在C中所用的动态分配的struct数组。

以下是如何将其纳入您的代码的方式(未经测试)...

#include <vector>
#include <iostream>

struct Point
{
    int x;
    int y;
};

typedef std::vector<Point> PointVector;

int main()
{
    using std::cout;
    using std::cin;
    using std::endl;

    PointVector points;

    char command = 0;
    do
    {
        cout << "n - Create new point." << endl;
        cout << "q - Quit." << endl;
        cout << "Input a new command: ";
        cin >> command;

        if (command == 'n')
        {
            Point new_point;
            new_point.x = 1;
            new_point.y = 1;
            points.push_back(new_point);
            cout << "(" << new_point.x << "," << new_point.y << ")\n";
        }
        else if (command == 'q')
        {
            for (PointVector::iterator it = points.begin(), end = points.end();
                it != end;
                ++it)
            {
                cout << "(" << it->x << "," << it->y << ")\n";
            }
            break;
        }
        else
        {
            cout << "Please, enter a correct command." << endl;
        }
    } while(true);
}

关键点:

  1. typedef通常使代码更易读。
  2. std::vector::push_back()在不需要保持索引或过度关注大小的情况下,将元素添加到容器的末尾。
  3. 迭代器(例如由std::vector::begin()返回的迭代器)使得访问容器内的元素变得容易,同样不需要保持索引。参见为什么使用迭代器而不是数组索引?
  4. 这个实现不会像基于malloc()的实现一样泄漏points

我们如何处理points的内存管理呢?难道它不必在结束时删除吗? - locke14
@locke14: std::vectorallocator 会在 points 超出 scope 时处理它。points 绝不 应该手动进行 delete - johnsyweb
感谢澄清。如果points包含一个整数数组,那么数组的内存也会被释放吗? - locke14
1
即使如此!在现代C++中,您应该不需要调用delete!这是您周末的一些轻松阅读:http://herbsutter.com/elements-of-modern-c-style/ - johnsyweb

3

2

从代码看,您正在使用malloc来获取足够的内存以存储一个指向int的指针。不要使用malloc/free。这是C++,如果确实需要,请使用newdelete

值得庆幸的是,在这种情况下,您不必担心动态分配内存,因为您可以使用vector来完成所有操作,具体如下:

// First create a vector of points.
std::vector<Points> points;

// Now create the Point (i'm assuming you were going to read
// it from the input stream here.)
cin >> x >> y;
Point p;
p.x = x;
p.y = y;

// And add it to the vector.
points.push_back( p );

很简单,您不需要担心增加点向量的容量或在最后清除它。


1

您可以像@iedoc建议的那样使用向量:

#include <iostream>;
#include <vector>;

using namespace std;

struct SPoint
{
    int X;
    int Y;
};

int main()
{
    vector<SPoint> points;

    char command;
    do
    {
        cout << "n - Create new point." << endl;
        cout << "q - Quit." << endl;
        cout << "Input a new command: ";

        cin >> command;

        if (command == 'n')
        {
            int x = 0;
            int y = 0;

            cout << "X: ";
            cin >> x;

            cout << "Y: ";
            cin >> y;

            SPoint point = { x, y};
            points.push_back(point);
        }

        else if (command == 'q')
        {
            for (int i = 0; i < points.size(); ++i)
            {
                cout << "(" << points[i].X << "," << points[i].Y << ")";
            }

            return 0;
        }
        else
        {
            cout << "Please, enter a correct command."<<endl<<endl<<endl;
        }
    }

    while(true);

    return 0;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接