[英]is there any way to define dynamic array without Determine the size of it
I need a dynamic array that I don't have to scale(Determine) to a fixed number like the following我需要一个不需要缩放(确定)到固定数字的动态数组,如下所示
string* s;
I have this code so far, but obviously it doesn't work.到目前为止我有这个代码,但显然它不起作用。
#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;
}
This is my task:这是我的任务:
Now we change the class definitions a bit.
现在我们稍微更改 class 定义。 No static arrays can occur anymore.
不会再出现 static arrays 了。 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).
arrays 变成动态的事实意味着需要修改一些 class 方法,并且一些/一些类需要复制构造函数和赋值方法(或叠加赋值运算符)。 [...]"
[...]”
This means, that I just can't use data structures.这意味着,我不能使用数据结构。
It's not automatic, you have to allocate more memory every time you want to resize, copy elements into new array and delete the old one.这不是自动的,每次你想调整大小时,你必须分配更多的 memory,将元素复制到新数组中并删除旧数组。 Fortunately, standard library got you covered with
std::vector
- an automatically resizable array.幸运的是,标准库为您提供了
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;
}
I also fixed your input reading - see Why is iostream::eof inside a loop condition (ie while (.stream.eof())
) considered wrong?我还修正了您的输入读数 - 请参阅为什么 iostream::eof 在循环条件内(即
while (.stream.eof())
)被认为是错误的? (applies to good()
as well). (也适用于
good()
)。
Alternatively, you can use std::istream_iterator
to initialize vector in one line instead of using loop (credit to Ayxan ):或者,您可以使用
std::istream_iterator
在一行中初始化向量,而不是使用循环(归功于Ayxan ):
vector<string> s{ istream_iterator<string>{f}, {} };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.