Wanna create a dynamic array without malloc under c++? Consider using vector. We need a dynamic array that can allow us delete any elements at any position, delete all elements, insert any element at any position. Bellow is an example code that does all of those requirements.
#include<vector>
#include<cstdio>
using namespace std;
int main()
{
vector<int> dyarray;
int a=7;
dyarray.push_back(a);
dyarray.push_back(8);
dyarray.push_back(a+2);
for (a=0;a<dyarray.size();a++)
printf("%d ",dyarray[a]);
printf("\n");
//delete second element
a=1; //second element
dyarray.erase(dyarray.begin()+a);
printf("size %d\n",dyarray.size());
for (a=0;a<dyarray.size();a++)
printf("%d ",dyarray[a]);
printf("\n");
//insert at position 2
dyarray.insert(dyarray.begin()+1,3);
printf("size %d\n",dyarray.size());
for (a=0;a<dyarray.size();a++)
printf("%d ",dyarray[a]);
printf("\n");
//delete all
dyarray.clear();
printf("size %d\n",dyarray.size());
return 1;
}
Output :
7 8 9
size 2
7 9
size 3
7 3 9
size 0
It should be easy to understand and need no further explanation. Vector declaration is a bit awkward if you didn’t experience it before.
vector<int> dyarray;
It create a new vector dyarray container to store dynamic integer element. You can define a structure or even class and create a vector of your structure or class.
#include<vector>
#include<cstdio>
#include<cstring>
using namespace std;
typedef struct _MYSTRUCT
{
int id;
char name[128];
}MYSTRUCT;
int main()
{
vector dystruct;
MYSTRUCT mystruct;
mystruct.id=3;
strcpy(mystruct.name,"my name");
dystruct.push_back(mystruct);
printf("%s, %d\n", mystruct[0].name, mystruct[0].id);
....
It happens vector only supported in c++, that is only the bad thing I can say. There a lots more function, check out the reference.
Reference:
http://www.sgi.com/tech/stl/Vector.html
How about iterators instead of loops?
THXXXX