c++ - 在 C++ 中动态分配字符串数组
问题描述
我已经在 CPP 中分配了一个初始大小的字符串数组,我需要根据计数器动态调整它的大小。
这是初始化语句:string buffer[10]; 我需要根据计数器调整它的大小。cpp中是否有realloc函数?
解决方案
您应该使用类似链接列表的东西,例如std::vector
或std::list
这样做,这里有一个例子:
#include <iostream>
#include <stdlib.h>
#include <string>
#include <list>
using namespace std;
int main()
{
list<string> buffer;
int count = 0;
while (true)
{
string s;
cin >> s;
if (s._Equal("exit"))
break;
buffer.push_back(s);
count++;
}
cout << endl << endl << "We have a total of " << count << " string(s):";
for (auto i = buffer.begin(); i != buffer.end(); i++)
cout << endl << "- " << (*i).c_str();
cout << endl << endl;
system("pause");
return 0;
}
链接:std::vector
std::vector 是封装动态大小数组的序列容器。
推荐阅读
- python - 如何提取数据框对象内列表中的第一个单词?
- php - 将数据库中的列转换为数组 Php
- spring - Tomcat 未重定向到 index.html
- python - 无法在 Windows 10 上的 Git-Bash 中为 Python 文档运行 Flask
- python - 延迟首付python的抵押贷款月供
- subquery - Ecto:子查询和存在
- node.js - nodejs -- 强制移动一个繁忙的目录
- angular - 如何使用 Angular 和 rxjs 保持长时间运行的 http post 请求?
- python - 正则表达式删除列数据框python中字符串的特定部分
- javascript - 从 div 获取 innerHTML 值 onclick(在 javascript 中)