gpt4 book ai didi

c++ - 该 vector 按哪个值排序?

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:45:11 24 4
gpt4 key购买 nike

我不太了解 C,但我想了解这段代码的工作原理。我的问题是我真的不明白在这种情况下如何对 vector 进行排序。它如何知道必须按哪个值对其进行排序?

#include "stdafx.h"
#include "LatticeLocation.h"
#include "Body.h"
#include "Region.h"
#include "Particle.h"
#include <queue>

void LatticeLocation::CalculateNeighborhood()
{
sort(neighborhood.begin(), neighborhood.end());
}

这是排序后的 vector :

std::vector<LatticeLocation*> neighborhood; 

这里是 LatticeLocation.h 文件:

#pragma once
#include "Point3.h"
#include <vector>

class Summation;
class Body;
class Chunk;
class Region;
class Particle;
class Cell;

class LatticeLocation
{
public:
Body *body;
Point3 index;
Cell *cell; // Primarily for rendering... we keep it in the physics engine to make things simple for users

// Properties
bool regionExists; // Set to false if the region is identical to another region or otherwise turned off
bool edge; // Whether this is an edge - i.e., has less than the full number of immediateNeighbors

// The IMMEDIATE immediateNeighbors
std::vector<LatticeLocation*> immediateNeighbors;
LatticeLocation *immediateNeighborsGrid[3][3][3]; // Same as the pointers in the array, just indexed differently

// Generated
std::vector<LatticeLocation*> neighborhood; // All particles up to w links away

// The elements centered/living here
Particle *particle;
Region *region; // MAY BE NULL
std::vector<Summation*> sums[2]; // Sums that live here (not necc. centered). sums[0] = xSums, sums[1] = xySums

// Used in some algorithms
unsigned int touch;
float touchFloat;

void CalculateNeighborhood(); // Will use a BFS to fill in neighborhood. Also sets regionExists
};

stdafx.h:

#pragma once

#include <string>
#include <sstream>

#include <math.h>
#include <fvec.h> // SSE
#include <vector>
#include <set>
#include <string>

#include <stdio.h>
#include <stdlib.h>
#include <algorithm>

我发现的所有排序示例都使用“std:sort”而不仅仅是“sort”,所以它可能不是这里使用的标准排序函数。我在所有源代码文件中搜索了这样一个排序功能,但没有。或者是否有一个标准的排序函数可以自动发现 LatticeLocation 包含一个可排序的值(Point3 索引,因为 Point3 重载了 < 运算符)并按该值对其进行排序?

编辑:

事实证明,我在上面的片段中遗漏了一些重要的代码。这应该更有意义

#include "stdafx.h"
#include "LatticeLocation.h"
#include "Body.h"
#include "Region.h"
#include "Particle.h"
#include <queue>

void LatticeLocation::CalculateNeighborhood()
{
neighborhood.clear();
neighborhood = immediateNeighbors;
sort(neighborhood.begin(), neighborhood.end());
}

最佳答案

如果你正在排序的 vector 是由指针 LatticeLocation* 组成的,那么你得到的排序就有点没有意义:你只是在排序指针(即你是根据对象在内存中占据的特定“随机”位置对对象进行排序),而不考虑 LatticeLocation 类的语义

您可能希望提供一个临时自定义排序标准,例如使用lambda 作为 std::sort() 的第三个参数:

sort(neighborhood.begin(), neighborhood.end(), [](const LatticeLocation* a, 
const LatticeLocation* b) {
// Implement proper code to specify if '*a' is less than '*b'
....
});

关于c++ - 该 vector 按哪个值排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22850323/

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