gpt4 book ai didi

c++ - 动态字符串数组 C++

转载 作者:行者123 更新时间:2023-11-28 03:20:50 32 4
gpt4 key购买 nike

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

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

关于c++ - 动态字符串数组 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15475438/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com