Monday, May 24, 2010

C++ How do I remove the last element of an array?

What do you mean? Arrays are a constant size in C++ the same as C. So you can't really remove elements entirely from them, unless you create a new array that is one shorter and copy the values (skipping the last one) into it.





BTW- You should look at using std:vector if you want something that is more dynamic but acts a lot like an array. There's not many reason to use C style arrays in C++ because vectors are so much nicer.

C++ How do I remove the last element of an array?
Well, you have to consider what an array in c/c++ is.


When you code


int array[20];


What you basicly do is say to the compiler:


'Hey, I want to use 20 integer numbers set up one after another'


What you get is a pointer to the first element. You have to remember that this is static memory consumption thingie, and the memory can't be recovered untill the variable is out of range.





Were you to use this construct


int *array = new int[20];


You'd get 20 integers in a row in dynamic memory.


then you could do


int *array2= new int[19];


for(int i=0;i%26lt;19;i++) array2[i]=array[i];


delete(array);


array=array2;


This way your array's last element is gone, but you kinda have rewritten the array into another place..
Reply:An STL vector is a generic array, and much more powerful than a plain-old-data array. Removing the last element of a vector is easy. Here's an example:





#include %26lt;iostream%26gt;


#include %26lt;vector%26gt;





using namespace std;





const int VEC_LEN = 4;


void printVec(const vector%26lt;int%26gt;%26amp;);





int main(int argc, char *argv[]) {


vector%26lt;int%26gt; intVec;





// fill vector and print it


for (int i = 0; i %26lt; VEC_LEN; i++) {


intVec.push_back(i);


}


printVec(intVec);





// remove last element, and print


intVec.pop_back();


printVec(intVec);





return 0;


}





void printVec(const vector%26lt;int%26gt;%26amp; v) {


for (vector%26lt;int%26gt;::const_iterator iter = v.begin();


iter != v.end(); ++iter) {


cout %26lt;%26lt; *iter %26lt;%26lt; " ";


}


cout %26lt;%26lt; endl;


}





Program output:


0 1 2 3


0 1 2
Reply:U can't remove elements from any array but in linklist


No comments:

Post a Comment