首页 > 解决方案 > 在 C++ 中动态分配字符串数组

问题描述

我已经在 CPP 中分配了一个初始大小的字符串数组,我需要根据计数器动态调整它的大小。

这是初始化语句:string buffer[10]; 我需要根据计数器调整它的大小。cpp中是否有realloc函数?

标签: c++dynamic

解决方案


您应该使用类似链接列表的东西,例如std::vectorstd::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 是封装动态大小数组的序列容器。


推荐阅读