C++怎样声明一个长度不定的数组?

above!

#include<iostream>

#include<vector>

#include<algorithm>

#include<functional>

#include<iterator>

using namespace std;

int main()

{

  vector<int> ivec;

  cout<<"input the num";

  int num;

  while(cin>>num)

   {

      ivec.push_back(num);

   }

  cout<<"the size of the array is "<<ivec.size()<<endl;

  sort(ivec.begin(),ivec.end());

  cout<<" 排序后";

  copy(ivec.begin(),ivec.end(),ostream_iterator<int>(cout," "));

  return 0;

}

温馨提示:内容为网友见解,仅供参考
第1个回答  推荐于2017-11-26
int *a,i; //定义一个指针,i表示数组个数
a=new int[i];//用new先创建他的空间
delete a;//删除

使用时和普通数组差不多,a[0]~a[i-1];

楼上说的没错,长度不定的数组好像是不存在。本回答被网友采纳
第2个回答  2013-03-30
可以用指针。

char *p = malloc(0);//分配一个0长度的字符串数组。
那么改变它容量的办法就是
p = (char*)realloc(p,新大小);
最后要通过
free(p);来释放它占用的空间。

长度不定的数组好象是不存在的。
第3个回答  2013-03-30
数组必须指定长度的,,因为系统需要为你准备.
不过你可以用链表,链表可以为你动态开辟内存,即当你需要增加一个数据时,你向系统索要一块内存.不知道链表的话可以再问
第4个回答  2013-03-30
C++的话直接用Vector向量就成了啊!!!
相似回答