有什么方法可以定义动态数组而无需确定其大小

问题描述

我需要一个动态数组,不必像以下那样将其缩放(确定)为固定数

string* s;

到目前为止,我已经有了这段代码,但是显然不起作用。

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main()
{
    fstream f;
    f.open("resa.txt");
    string* s;
    int i = 0;
    while (f.good())
    {
        f >> *(s + i);
        i++;
    }
    return 0;
}

这是我的任务:

现在,我们稍微更改类定义。不再有静态数组。数组变为动态的事实意味着需要修改某些类方法,并且某些/某些类需要复制构造函数和赋值方法(或叠加赋值运算符)。 [...]“

这意味着,我只是不能使用数据结构。

解决方法

这不是自动的,每次您要调整大小,将元素复制到新数组并删除旧数组时,都必须分配更多的内存。幸运的是,标准库使您可以使用std::vector-一种可自动调整大小的数组。

#include <iostream>
#include <string>
#include <fstream>
#include <vector>

using namespace std;

int main()
{
    fstream f;
    f.open("resa.txt");
    string temp;
    std::vector<std::string> s;
    while (f >> temp)
    {
        s.push_back(temp);
    }
    return 0;
}

我还修复了您的输入内容-请参见Why is iostream::eof inside a loop condition (i.e. while (!stream.eof())) considered wrong?(也适用于good())。


或者,您可以使用std::istream_iterator在一行中初始化矢量,而不是使用循环(贷记到Ayxan):

vector<string> s{ istream_iterator<string>{f},{} };