gpt4 book ai didi

c++ - 使用 vector 中的对象排序

转载 作者:行者123 更新时间:2023-11-30 02:39:22 26 4
gpt4 key购买 nike

我有一个函数可以进行一些计算并将返回的值设置到我的 vector 中。

#include <vector>
#include <algorithm>
#include <iostream>

void VectorLoop(vector<ClassName>& Vector)
{
float TempFloatVariable = 0.0;
int count = 0;
int update = 0;

while (count != Vector.size())
{
if (Vector[count].getValue() == 100.0) //I hardcode this so i can check if the Value is empty or not
{
//code that set all of the variable from the vector's memory's object

TempFloatVariable = AnotherClass.Formula //does the computing and return the value
//code that gets value from object for overloading
//code that gets value from object for overloading
//code that gets value from object for overloading

Vector[count].setValue(TempFloatVariable);
update++;
}
else
{
count++;
}
}

cout << "Computation completed! (" << update << " record(s) were updated)" << endl;
}

完成所有计算后,我想根据值从高到低对它们进行排序,但我不知道该怎么做,我尝试对其进行硬编码,手动将值 1 乘 1 地提取出来做比较,但一直失败。这会破坏使用 vector 的目的,有很多使用 vector 进行排序的示例,但其中 90% 是存储在 vector 中的 int 值。

最佳答案

正如 IgorTandetnik 所说:你可以做到

std::sort(Vector.begin(), Vector.end(), [](const PointTwoD& a, const PointTwoD& b)
{
return a.getcivIndex() > b.getcivIndex();
});

它将使用 lambda 的结果对 vector 进行排序,并且应该按照您的意愿进行。

要打印 vector 中的对象,您应该这样做:

for(int i = 0; i < Vector.size(); i++)
{
std::cout << Vector[i] << std::endl; //Or whatever your printing function is.
}

这将遍历 vector 中的所有对象,并且由于它们应该已经按降序排列,因此它将按照您想要的降序打印出来。

编辑:

对于非 C++11 用户:您可以定义一个函数来进行比较

bool compare(const PointTwoD& a, const PointTwoD& b)
{
return a.getcivIndex() > b.getcivIndex();
}

并使用它代替 lambda。像这样:

std::sort(Vector.begin(), Vector.end(), compare);

关于c++ - 使用 vector 中的对象排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29870148/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com