Vector properties in C++ - sorting,erase,accessing elements - UCS - Unleash-Coding-Skills

Saturday, 24 March 2018

Vector properties in C++ - sorting,erase,accessing elements - UCS


Vectors :

We have seen about vector declaration and size concepts in this post

Now we can go through furthur properties in vectors.

Erasing an element in vector:

If we use pop_back(), we’ll remove the last element.

v.pop_back(); 


To remove the first element, we can use erase(). We need to pass the element’s position (iterator position), we want to remove, as an 

v.erase(v.begin());

We can also remove the last element using erase.

v.erase(v.begin() + v.size() - 1);

clearing the vector in cpp so that it become empty.

v.clear();

Using the first element in vector.

v.front();

or 

v[0];


Using last element in vector.

v.back();

 or

v[v.size()-1];

Sorting the vector in cpp:

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

Vector is ascending order after sorting.

To get in descending order the syntax is.

sort(v.begin(), v.end(), greater<int>());

To implement sorting we have to include the header.

#include<algorithm> 

Example for sorting of vector:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int>v;
    v.push_back(10);
    v.push_back(7);
    v.push_back(20);
    v.push_back(100);
    v.push_back(35);
    int sum=0;
    sort(v.begin(),v.end());
for(int i=0;i<v.size();i++)
{
      cout<<v[i]<<" ";

}

    return 0;
}

output:

7 10 20 35 100 

We can also sort up to a index in vector by using:

sort(v.begin()+value,v.end());

example:
 In our above program if the sort line be like

sort(v.begin()+2,v.end());

The output order is

10 7 20 35 100 

So we have control in which range we have to sort our vector this advantage can be used very much in programs.

No comments:

Post a comment