vendredi 29 mai 2015

Sorting vectors in c++

I need to sort the data structure vector<pair<unsigned, pair<vector<unsigned>, vector<unsigned> > > > sbp first by sbp.second.second vector and for equal values of sbp.second.second by sbp.second.first -- both the vectors are compared by (i) size of vectors; (ii) if size of vectors are equal, then vectors are lexicographically sorted. For doing so, I wrote the following code. But I dont know why but this code is getting stuck in an infinite loop. Can someone please help me with as to where am I going wrong.

#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
typedef std::pair<std::vector<unsigned>, std::vector<unsigned> > vec_pair;

bool sortingFunc(const pair<unsigned,vec_pair>& a, const pair<unsigned,vec_pair>& b)
{
    if((a.second).second.size() == (b.second).second.size()) {
        if(std::lexicographical_compare((a.second).second.begin(), (a.second).second.end(), (b.second).second.begin(), (b.second).second.end()))//a<b
        {
            return true;
        }else{
            if((a.second).first.size() == (b.second).first.size()) {
                return std::lexicographical_compare((a.second).first.begin(), (a.second).first.end(), (b.second).first.begin(), (b.second).first.end());
            } else {
                // Sort by size.
                return (a.second).first.size() < (b.second).first.size();
            }            
        }
    } else {
        // Sort by size.
        return (a.second).second.size() < (b.second).second.size();
    }
}

int main()
{
    vector<pair<unsigned, pair<vector<unsigned>, vector<unsigned> > > > sbp;
    std::sort(sbp.begin(), sbp.end(), sortingFunc);
}

I am using C++11 (gcc 4.8.2)

Aucun commentaire:

Enregistrer un commentaire