【问题标题】:How do I Increase the size of a Class array? in turbo c++如何增加 Class 数组的大小?在涡轮 C++
【发布时间】:2018-01-08 12:09:40
【问题描述】:

我写了这门课:

class Spacewalk {
private: 
    char mission[50];
    char date[50];
    char astronaut[50];
    char startingAt[50];
    char endingAt[50];
public:
    void list() {
       // lists the values.
    }
    void addValue(miss, da, astro, start, end) {
         // adds value to the private items.
    }
};

我创建了这个类的数组,像这样-

Spacewalk list[1]; 

比方说,我已经用完了这个数组的空间,我该如何增加它的大小?

【问题讨论】:

  • std::vector<T> x;代替T x[N];,那么你可以.resize或者.push_back
  • 您可以使用std::vector<Spacewalk>。也许std::string 而不是 char 数组?
  • 你指的是那个吗? stackoverflow.com/questions/12032222/…
  • 问题是 std 在 turbo c++ 中不可用,我们该死的学校强迫我们使用它。
  • @DakshMiglani 标准库是 c++ 的一个组成部分。学习 c++ 而不访问标准库就像学习没有元音的读写一样。

标签: c++ arrays turbo-c++


【解决方案1】:

数组非常适合学习编码的概念,因此我比任何其他标准模板库(在学习代码方面)更赞同它们。

注意:
使用vector 是明智的,但是学校不教这个的原因是因为他们希望您了解vectorstackqueue 等事物背后的基本概念。如果不了解汽车的零件,就无法制造汽车。

遗憾的是,在调整数组大小时,除了创建一个新数组并传输元素之外,没有其他简单的方法。最好的方法是保持数组动态。

请注意,我的示例适用于 int(s),因此您必须将其制成模板或将其更改为所需的类。

#include <iostream>
#include <stdio.h>
using namespace std;


static const int INCREASE_BY = 10;

void resize(int * pArray, int & size);


int main() {
    // your code goes here
    int * pArray = new int[10];
    pArray[1] = 1;
    pArray[2] = 2;
    int size = 10;
    resize(pArray, size);
    pArray[10] = 23;
    pArray[11] = 101;

    for (int i = 0; i < size; i++)
        cout << pArray[i] << endl;
    return 0;
}


void resize(int * pArray, int & size)
{
    size += INCREASE_BY;
    int * temp = (int *) realloc(pArray, size);
    delete [] pArray;
    pArray = temp;

}

【讨论】:

    猜你喜欢
    • 2016-10-12
    • 2013-11-30
    • 1970-01-01
    • 2018-04-14
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多