While programming use of arrays is very common and almost everyone even the beginner knows about it. Now we know that array is a contiguous memory location of fixed size . Here the problem begins that we cannot increase the size of an array later during run time thus we need to declare a very large array and a lot of memory is wasted . So here is the solution , Vectors in simple terms are expandable arrays . Not talking much let's get straight to an example .
here we are creating a vector named v1 of integer type (surely you can go for any data type ) then we inserted 3 integers from the end then i show usage of various functions . After clearing next we insert two more integers so first we had the size 3 and now we have size 2 that means flexible size . Also we can directly acess any element by writing v1[index]
C++ Program :
/* vector in common language is a expandable array with large number of functionalities */
#include <iostream>
#include <vector>
using namespace std;
int main ()
{
vector<int> v1;
int sum=0 ,i;
v1.push_back (1);
v1.push_back (2);
v1.push_back (3);
cout<<"\n second element is "<<v1[1]<<"\n";
while (!v1.empty())
{
sum+=v1.back();
v1.pop_back();
}
cout << "The elements of v1 add up to " << sum << '\n';
v1.clear();
v1.push_back (1101);
v1.push_back (2202);
cout << "v1 contains:";
for ( i=0; i<v1.size(); i++)
cout << ' ' << v1[i];
cout << '\n';
}
No comments:
Post a Comment
THANKS FOR UR GREAT COMMENT