Vectors
VECTORS
First of all include the header #include<vector> in file;
The capacity of the vector at the time it is initialised is 0,
when value is stored in it, its capacity first increases by 1 and
then gets doubled each time the capacity of the vector lacks.
Vector <datatype> vector_name; //creates vector of size zero.
Vector <datatype> vector_name(n);//creates vector of size n.
vector_name.push_back(any number);//to insert any number in the vector and the value gets inserted in the one by one order.
vector_name.pop_back(); //pops out the last element from the vector.
This function does not reduces the size of the vector once increased by push_back() function.
To enter the elmts in vector with help of loop.
for(i=0; i<n; i++)
{
cin>>a;
vector_name.push_back(a);
}
vector_name.size(); // returns the number of elements filled in vector.
vector_name.capacity(); //returns the capacity of the vector.
vector_name.clear(); // is used to empty the vector.
We can also sort the vector as follows;
vector<datatype>v_name;
sort(v_name.begin(),v_name.end());
ex- In this we have sorted the vector in ascending order and printed
it with help of iterator.
int main()
{
vector<int> v{ 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 };
sort(v.begin(), v.end());
cout << "Sorted \n";
vector<int>::iterator ptr;
for(ptr=v.begin();ptr<v.end();ptr++)
cout<<*ptr;
Or
for(int i=0;i<v.size();i++)
cout<<v[i];
return 0;
}
use sort(v.begin(), v.end(),; // to sort the vector in
descending order.
To compare two vectors.
output:
Equal
Not Equal
Not Equal
Equal
Comments
Post a Comment