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

标签 c++ arrays dynamic

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

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/

相关文章:

html - 如何使一组图像超出容器 div 的宽度?

Objective-C:覆盖动态 setter/getter

c++ - SDL、标题和奇怪的错误..?

C++ 跨平台 zlib simplifer-wrapper

c++ - CComSafeArray 使用

java - ArrayList 图书搜索

c# - 通用类型参数和动态类型

c++ - 创建良好的目录结构

php - MySQLi PHP -> 使用获取数组时 LEFT JOIN 返回 Null

javascript - 在 VUE js 中获取数组中数据的索引