0

我创建了一个固定长度的字符串:

string fileRows[900];

但有时我需要超过 900 个,有时 500 个就足够了。

之后我需要用文件行填充数组:

...
    string sIn;
    int i = 1;

    ifstream infile;
    infile.open(szFileName);
    infile.seekg(0,ios::beg);

    while ( getline(infile,sIn ) ) // 0. elembe kiterjesztés
    {
        fileRows[i] = sIn;
        i++;
    }

如何为这个数组创建动态长度?

4

1 回答 1

2

使用std::vector,向量被称为动态数组:

#include <vector>
#include <string>

std::vector<std::string> fileRows(900);

实际上,您可以为元素保留空间并调用push_back

std::vector<std::string> fileRows;
fileRows.reserve(900);   

while (std::getline(infile, sIn))
{
   fileRows.push_back(sIn);
}
于 2013-03-18T11:15:54.393 回答