Search code examples
c++arrayssortingvectorstdvector

How to sort an array of vectors in c++?


I have created an array of vectors. After taking the input I have to sort them, I guess I need to use a comparator function but I cannot understand how do I use it.

int main()
{
    
    int  n, k;
    cin >> n >> k;
    vector<long long> times[4];
  
    for (int i = 0; i < n; ++i)
    {
        ll t, a, b;
        cin >> t >> a >> b;
        times[a * 2 + b].push_back(t);
    }

    cout << times[0].size();
    ***//i need to sort the whole of times[0] after this***
}

Solution

  • For ascending order,

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

    For Descending order,

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

    Another way,

        void cmp(ll a, ll b) { 
          return a < b;  
        }
    
      // Use the below statement anywhere you want - 
        sort(times.begin(),times.end(),cmp);