c++ - 基于对 vector 中第一个元素的降序排序没有给出期望的结果

标签 c++ c++11 vector stl std-pair

在下面的共享代码链接中,根据对的第一个元素按降序对 vector 元素进行排序,但看起来排序没有发生,也没有收到预期的输出。这里需要打印第一个迭代值降序排列,下同 代码写在 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. vector 的静态声明,以便将此 vector 与 所有对象。
  2. iterateVector 也需要声明为静态(访问静态 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;  
    }
    

关于c++ - 基于对 vector 中第一个元素的降序排序没有给出期望的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59509174/

相关文章:

c++ - unsigned char 类型的负数

c++ - 有没有办法增加数组的内存?和相关问题

java - 将数组保存在 Vector 中并再次取出

r - 在 R 中将函数与矢量参数集成

matlab - 如何找到至少包含矢量 B 的一个元素的单元格 A 的矢量?

c++ - 如何在不修改其现有内容的情况下使用 C++ 填充 csv 文件中的列?

c++ - 使用模板的构造函数链接器错误

c++ - std::pair: 过于严格的构造函数?

c++ - Clang 定义了什么宏来宣布 C++11 模式(如果有)?

c++ - 多重延续链接 : boost. future 展开。怎么做