在下面的共享代码链接中,根据对的第一个元素按降序对 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
最佳答案
您可以通过以下方式修复此问题:
- vector 的静态声明,以便将此 vector 与 所有对象。
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/