c++ - C++中的动态内存点

标签 c++ arrays algorithm memory-management dynamic-memory-allocation

我正在尝试用 C++ 编写代码,从文件中读取一系列点,将其存储在动态数组中,然后打印回来。

这是我得到的规范:

“我们想利用我们可以使用动态内存这一事实,因此我们实现了以下算法,而不是根据我们的估计在开始时分配足够大的内存量:

最初,分配的内存很少。

在循环的每次迭代中(从文件中读取并存储到 动态数组)我们跟踪:

  • 数组的最大大小(分配的内存)。
  • 数组中元素的数量。

当因为新的插入,元素的数量会变成 大于数组最大大小,需要重新分配内存 放置如下:

  • 分配另一个具有更大最大大小的动态数组。
  • 将前一个数组中的所有元素复制到新数组中。
  • 释放为前一个数组分配的内存区域。
  • 获取指向前一个数组的指针以指向新数组。
  • 在数组末尾添加新项目。这就是我的问题所在。

从我下面的代码来看,我认为其他一切都很好,但最后一个要求是在数组末尾添加新项目。

The code works fine when the array Max_Size exceeds file's number of elements, but when I try extending the num_elements, the result is that the extra digits in the file are just saved as zeros

.

Also to add, the assignment doesn't allow use of vectors just yet. Sorry I forgot to mention this, I'm new to stackoverflow and somewhat to programming.

请帮忙

#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;

struct point {  
    double x;
    double y;
};

int main () {

    ifstream inputfile;

    inputfile.open("datainput.txt");

    if(!inputfile.is_open()){
    cout << "could not open file" << endl;
        exit(EXIT_FAILURE);
    }

    //initially very little memory is allocated
    int Max_Size = 10;
    int num_elements = 0;
    point *pp = new point[Max_Size];


    //read from file and store in dynamic array
    for (int i = 0; !inputfile.eof(); i++) {
            inputfile >> pp[i].x >> pp[i].y;
            num_elements++;                 //keep track of number of elements in array
        }


    //detecting when number of elements exeeds max size due to new insertion:
    if (num_elements > Max_Size){

        // allocate another dynamic array with a greater maximum size
        Max_Size *= 2;              // Max_Size = 2*Max_Size to double max size whenever there's memory problem
        point *pp2 = new point[Max_Size];

        //copy all elements from previous array to new one
        for (int j=0; j<(Max_Size/2); j++) {
            pp2[j].x = pp[j].x ;
            pp2[j].y = pp[j].y;
        }


        //deallocate memory area allocated for previous array
        delete [] pp;

        //get pointer to previous array to point to the new one
        pp = pp2;





 **//add new item at end of the array
        for (int k = ((Max_Size/2)-1); k<num_elements; k++) {
                     inputfile.seekg(k, ios::beg) >> pp2[k].x;
                     inputfile.seekg(k, ios::beg) >> pp2[k].y;

                }**


        //print out dynamic array values
        for (int l = 0; l<num_elements; l++) {
            cout << pp2[l].x << ",";    
            cout << pp2[l].y << endl; 
        }

        //delete dynamic array
        delete [] pp2;
    }

    else {
        //print out dynamic array values
        for (int m = 0; m<num_elements; m++) {
            cout << pp[m].x << ","; 
            cout << pp[m].y << endl; 
        }

        //delete dynamic array
        delete [] pp;
    }   

    cout <<"Number of elements = " << num_elements <<endl;




    //close file
    inputfile.close();

    return 0;
}

最佳答案

其他人已经指出了std::vector。使用它的代码大致如下所示:

#include <vector>
#include <iostream>

struct point {
    double x;
    double y;

    friend std::istream &operator>>(std::istream &is, point &p) { 
        return is >> p.x >> p.y;
    }

    friend std::ostream &operator<<(std::ostream &os, point const &p) { 
        return os << p.x << "," << p.y;
    }
};

int main() { 
    // open the file of data
    std::ifstream in("datainput.txt");

    // initialize the vector from the file of data:
    std::vector<point> p {
        std::istream_iterator<point>(in),
        std::istream_iterator<point>() };

    // print out the data:
    std::copy(p.begin(), p.end(), std::ostream_iterator<point>(std::cout, "\n"));
}

除了比您发布的代码更短更简单之外,让它工作可能会简单得多,而且(锦上添花)它几乎肯定会运行得更快1(尤其是当您有大量数据时)。


<支持> 1. 公平地说,我觉得有必要指出速度上的差异主要来自于使用 \n 而不是 endl 来终止每行。这避免了在写入每一行时刷新文件缓冲区,这很容易使速度提高一个数量级。另请参阅:https://stackoverflow.com/a/1926432/179910

关于c++ - C++中的动态内存点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25385520/

相关文章:

c++ - 如何使用虚函数返回指向基类的指针?

c++ - 有没有一种简单的方法可以根据标准的命名要求测试您的代码?

ios - Swift - 如何检查数组中是否存在具有某些属性的元素?

java - 从多个数字 ID 创建唯一的数字 ID

java - 快速排序霍尔数组分区

algorithm - 使用重复值快速选择

c++ - Arch Linux 中没有 OpenGL 3 头文件

c++ - 库 header 在 header 中不可见,但在 cmake 构建下的 .cpp 文件中完全可见。为什么?

arrays - Julia 截断数组数组的内部维度

java - 零长度数组在内存中是如何表示的?