Sorting vectors in c++ -


i need sort data structure vector<pair<unsigned, pair<vector<unsigned>, vector<unsigned> > > > sbp first sbp.second.second vector , equal values of sbp.second.second sbp.second.first -- both vectors compared (i) size of vectors; (ii) if size of vectors equal, vectors lexicographically sorted. doing so, wrote following code. dont know why code getting stuck in infinite loop. can please me 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 size.                 return (a.second).first.size() < (b.second).first.size();             }                     }     } else {         // sort 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 using c++11 (gcc 4.8.2)

i use std::tie or make_tuple rvalue:

bool sortingfunc(const pair<unsigned, vec_pair>& a, const pair<unsigned, vec_pair>& b) {     return std::make_tuple(a.second.second.size(), std::ref(a.second.second), a.second.first.size(), std::ref(a.second.first))          < std::make_tuple(b.second.second.size(), std::ref(b.second.second), b.second.first.size(), std::ref(b.second.first)); } 

your case not correct with

if(std::lexicographical_compare((a.second).second.begin(), (a.second).second.end(), (b.second).second.begin(), (b.second).second.end()))//a<b {     return true; } 

where misses b < a condition.

else if(std::lexicographical_compare((b.second).second.begin(), (b.second).second.end(), (a.second).second.begin(), (a.second).second.end()))//b < {     return true; } 

before == condition.


Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -