基于对向量中第一个元素的降序排序没有给出预期的结果

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

在下面的共享代码 link 中,根据对的第一个元素按降序对向量元素进行排序,但看起来排序没有发生并且预期输出不是 received.Here第一个迭代值需要按降序打印,下同 代码写在 iterateVector() 函数中。

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

实际输出:

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

预期输出:

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

您制作了四个向量,每个向量都有一个元素。 没有一个包含四个元素的向量。

您可以通过以下方式解决此问题:

  1. 向量的静态声明,以便将此向量与 所有对象。
  2. iterateVector也需要声明为static(访问静态向量)

    #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;  
    }