动态字符串数组c++

dynamic string array c++

本文关键字:c++ 数组 字符串 动态      更新时间:2023-10-16

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

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

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

使用std::vector, 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);
}