Search code examples
c++c++11vectorstlstd-pair

Descending order sorting on basis of first element in vector of pair is not giving desired results


In below shared code link ,Sorting the vector elements on the basis of first element of pairs in descending order is performed but it looks like sorting is not happening and expected output is not received.Here first iterative value needs to be printed in descending order and for the same below code is written in iterateVector() function.

sort(vect.begin(),vect.end(),[] (const pair<double,double> &a,
const pair<double,double> &b){return (a.first > b.first);});  

http://coliru.stacked-crooked.com/a/d868271155375b17

Actual output:

first iterative value =30 second iterative value=300
first iterative value =45.3 second iterative value=300
first iterative value =23 second iterative value=301
first iterative value =175 second iterative value=303

Expected output:

first iterative value =175 second iterative value=303
first iterative value =45.3 second iterative value=300
first iterative value =30 second iterative value=300
first iterative value =23 second iterative value=301

Solution

  • You can fix this by :

    1. static declaration of vector in order to associate this vector with all objects.
    2. iterateVector also needs to be declared static (Access the static vector)

      #include <iostream>
      #include <vector>
      #include<algorithm>
      #include<memory>
      
      class State
      {
      public:  
      static void iterateVector();
      explicit State
      (
      const double& stateValue,
      const double& stateCommand
      )
      : _stateValue(stateValue),_stateCommand(stateCommand)
      {  
        _mvect.push_back( std::make_pair(_stateValue,_stateCommand) );
      }
      
      private: 
      const double& _stateValue;
      const double& _stateCommand;
      static std::vector< std::pair <double,double> > _mvect ;
      };
      
      void State::iterateVector()
      {
      
       sort(_mvect.begin(),_mvect.end(),[] (const std::pair<double,double> &a,
       const std::pair<double,double> &b){return (a.first > b.first);});       
       for (auto &itr : _mvect )
       {
         std::cout<<"first iterative value ="<<itr.first<<" ";
         std::cout<<"second iterative value="<<itr.second<<std::endl;
       }   
      
      }
      
      std::vector< std::pair <double,double> > State::_mvect ;
      int main()
      {
      
       std::vector< std::pair <double,double> > vect ;
       std::vector<std::unique_ptr<State> > obj;
       obj.emplace_back(std::move(new State(30,300)));
       obj.emplace_back(std::move(new State(45.3,300)));
       obj.emplace_back(std::move(new State(23,301)));
       obj.emplace_back(std::move(new State(175,303)));
       State::iterateVector();   
       return 0;  
      }