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

标签 c++ arrays dynamic

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

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;
}
这是我的任务:

Now we change the class definitions a bit. No static arrays can occur anymore. The fact that the arrays instead become dynamic means that some class methods need to be modified, and that some / some of the classes need copy constructors and assignment methods (or superimposed assignment operator). [...]"


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

最佳答案

这不是自动的,每次您要调整大小,将元素复制到新数组并删除旧数组时,都必须分配更多的内存。幸运的是,标准库使您可以使用 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 在一行中初始化 vector ,而不是使用循环(贷给Ayxan):
vector<string> s{ istream_iterator<string>{f}, {} }; 

关于c++ - 有什么方法可以定义动态数组而无需确定其大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63425723/

相关文章:

java - 从数组中删除重复项并写入文本文件

javascript - 将数组中的多个元素移动到数组中的某个索引

c++ - 递归快速排序导致段错误(不是溢出)

c# - native 动态 Linq (C#)

c++ dirent.h 和获取绝对路径的语法

c++ - '未在此范围内声明'C++

c++ - 堆栈展开动态创建的对象,其构造函数也作用于堆

c++ - 用于部署 Qt 应用程序的文件

c - 使用动态数组的段错误

Javascript - 从未打开的页面访问元素