如何对类型为 <class*> 的向量进行排序?
How to sort a Vector of type <class*>?
可能的重复项:
C++如何使用运算符<对向量><类> 进行排序 类>对向量>
大家好!
请我尝试根据其数据成员之一对"类"类型的向量进行排序。如下:
头文件:(Undirected_Graph.h)
#ifndef UNDIRECTED_GRAPH_H
#define UNDIRECTED_GRAPH_H
#include <vector>
using std::vector;
#include <climits>
class Edge;
class Node
{
public:
Node(int); //The constructor.
int id; //For the id of the node.
bool visited; //For checking visited nodes.
int distance;
vector <Edge*> adj; //The adjacent nodes.
};
class Edge
{
public:
Edge(Node*, Node*, int); //The constructor.
Node* start_Node; //The start_Node start of the edge.
Node* end_Node; //The end of the edge.
int w; //The weight of the edge.
bool isConnected(Node* node1, Node* node2) //Checks if the nodes are connected.
{
return((node1 == this->start_Node && node2 == this->end_Node) ||
(node1 == this->end_Node && node2 == this->start_Node));
}
};
class Graph
{
public:
Graph(int); //The Constructor.
int max_Nodes; //Maximum Number of allowed Nodes.
vector <Edge*> edges_List; //For storing the edges of the graph.
vector <Node*> nodes_List; //For storing the nodes of the graph.
void insertEdge(int, int, int);
int getNumNodes();
int getNumEdges();
};
#endif
实施文件:(Undirected_Graph.cpp)
#include "Undirected_Graph.h"
Node::Node(int id_Num)
{
id = id_Num;
visited = 0;
distance = INT_MAX;
}
Edge::Edge(Node* a, Node* b, int weight)
{
start_Node = a;
end_Node = b;
w = weight;
}
Graph::Graph(int size)
{
max_Nodes = size;
for (int i = 1; i <= max_Nodes; ++i)
{
Node* temp = new Node(i);
nodes_List.push_back(temp);
}
}
void Graph::insertEdge(int x, int y, int w)
{
Node* a = nodes_List[x-1];
Node* b = nodes_List[y-1];
Edge* edge1 = new Edge(a, b, w);
Edge* edge2 = new Edge(b, a, w);
edges_List.push_back(edge1);
a->adj.push_back(edge1);
b->adj.push_back(edge2);
}
int Graph::getNumNodes()
{
return max_Nodes;
}
int Graph::getNumEdges()
{
return edges_List.size();
}
现在在上面的代码中,在创建多个节点和边缘后,我需要根据它们的权重对这个图的边缘进行排序。我正在研究一种实现 Kruskal 算法的方法,所以我首先根据边缘的权重对边缘进行排序。
sort (myGraph.edges_List[index].begin(), myGraph.edges_List[index].end());
显然是行不通的! 因为矢量edges_List的类型是"边缘"。假设(myGraph 是类的对象)。
我想知道是否有任何好的技术可以做到这一点?
提前感谢您的帮助!任何建议或想法将不胜感激!
默认情况下,std::sort
使用 using operator<
,但您也可以提供比较函数对象。
所以:
bool your_comparer(const Edge * left, const Edge * right)
{
// return true if left should come before right, false otherwise
}
// ...
sort (myGraph.edges_List.begin(), myGraph.edges_List.end(), your_comparer);
另一种方法是使用 std::set 容器来存储对象。而且您总是会整理容器。您所需要的只是为存储类定义operator <
。
就时间而言,带有push_back的使用向量不是有效的方法。它会导致不必要的内存重新分配。
相关文章:
- 将结构向量排序为子组
- C++数组与向量排序(在我的情况下,向量比数组慢~2.5倍(无优化))
- 如何在对向量排序后更改索引值?c++
- C++向量排序给出0作为输出
- 将许多向量排序在一起
- 根据一个向量对多个向量排序
- 编译错误向量排序和联合
- C++我自己的函数进行向量排序
- 将字符串的向量排序为日期"yyyymmdd"
- C++ 通过使用旧向量进行预排序来改进向量排序
- C 向量排序 .h .cpp中的单独文件
- 向量排序-c++
- 将向量排序到一个无序映射c++11中
- 向量的向量排序
- c++向量排序方法编译失败,返回预期表达式
- 如何对bitset向量排序
- 向量排序的基础上只有先
- 我如何以相同的方式对两个向量排序,而条件只使用其中一个向量
- 列表排序和结构体向量排序之间的性能差距.c++
- 如何基于第二个字符串对字符串向量的向量排序