繁体   English   中英

有没有办法定义动态数组而不确定它的大小

[英]is there any way to define dynamic array without Determine the size of it

我需要一个不需要缩放(确定)到固定数字的动态数组,如下所示

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;
}

这是我的任务:

现在我们稍微更改 class 定义。 不会再出现 static arrays 了。 arrays 变成动态的事实意味着需要修改一些 class 方法,并且一些/一些类需要复制构造函数和赋值方法(或叠加赋值运算符)。 [...]”

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

这不是自动的,每次你想调整大小时,你必须分配更多的 memory,将元素复制到新数组中并删除旧数组。 幸运的是,标准库为您提供了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;
}

我还修正了您的输入读数 - 请参阅为什么 iostream::eof 在循环条件内(即while (.stream.eof()) )被认为是错误的? (也适用于good() )。


或者,您可以使用std::istream_iterator在一行中初始化向量,而不是使用循环(归功于Ayxan ):

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM