Sorting in Vectors C++

We will use the builtin function sort() to sort the vector.

Header File: #include <algorithm>

Synatax: sort(first, last);

first -> first position in the sequence.
last  -> last position in the sequence

Sample Code:

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <vector>
#include <algorithm>


using namespace std;

void createVector(vector<int> &vect)
{
    srand(time(NULL));
    for (int i = 0; i < 10; i++)
        vect.push_back(rand()%100 + 1);
}

void displayVector(vector<int> vect)
{
    for (int i = 0 ; i < vect.size(); i++)
    {
        cout << vect[i] << endl;
    }
}



int main()
{
    vector<int> int_vector;
    createVector(int_vector);
    displayVector(int_vector);
    cout << endl;
    sort(int_vector.begin(), int_vector.end());
    displayVector(int_vector);
    cout << endl;

    return 0;
}

Comments

Popular posts from this blog

bb.utils.contains yocto

make config vs oldconfig vs defconfig vs menuconfig vs savedefconfig

PR, PN and PV Variable in Yocto