[英]Is there any way to make a char array without knowing what size it will be
[英]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.