本文介绍了如何排序对象std :: vector的浮点值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C ++ std :: vector表示为:

  std :: vector< GameObject *> vectorToSort; VectorToSort中的每个对象都包含一个通过调用DistanceFromCamera()返回的float参数:

p>

  vectorToSort.at(position) - > DistanceFromCamera 

我想通过这个float参数排序向量,但std ::排序看起来不能去做这个。如何实现这种类型?

解决方案

您想使用这样的谓词:

  struct VectorSortP {
bool operator()(const GameObject * a,const GameObject * b)const {
return a-> DistanceFromCamera )& b-> DistanceFromCamera();
}
};

std :: sort(vectorToSort.begin(),vectorToSort.end(),VectorSortP());


I have a C++ std::vector denoted as:

std::vector<GameObject*> vectorToSort;

Each object in vectorToSort contains a float parameter which is returned by calling "DistanceFromCamera()":

vectorToSort.at(position)->DistanceFromCamera();

I wish to sort the vector by this float parameter however std::sort does not appear to be able to do this. How can I achieve this sort?

解决方案

you want to use a predicate like this:

struct VectorSortP {
    bool operator()(const GameObject *a, const GameObject *b) const {
        return a->DistanceFromCamera() < b->DistanceFromCamera();
    }
};

std::sort(vectorToSort.begin(), vectorToSort.end(), VectorSortP());

这篇关于如何排序对象std :: vector的浮点值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 23:00