# Thread: Sorting a vector of objects

1. ## Sorting a vector of objects

I'm implementing kruskal's algorithm and ran into some troubles compiling. I need to sort a vector of objects by value. Here is my code and the error I'm getting.

Code:
```//These are the two functions in graph.cpp (there are more but are unrelated)
#include <vector>
#include <algorithm>
#include <iostream>

using namespace std;

#include "graph.h"
#include "edge.h"

using std::vector;

void graph::sort_edgesArray()
{
sort (edgesArray.begin(), edgesArray.end(), graph::cmp_val);   <== This is line 39 in the error
}

bool graph::cmp_val (edge& a, edge& B)
{
return (a.val < b.val);
}```
Code:
```//This is the header file graph.h
#ifndef GRAPH_H
#define GRAPH_H

#include <vector>
#include "edge.h"

using std::vector;

class graph
{
public:

int nEdges;
int nVerts;
vector<edge> edgesArray;            //array that holds edges
//might need a vertices vector

graph() :
nEdges(0),
nVerts(0)
{}

void addEdge(int start, int end, int value);

int get_edges();

int get_verts();

void sort_edgesArray();

bool cmp_val(edge& a, edge& b);
};

#endif```
Code:
```//This is the edge.h header file where graph.cpp is calling from to construct the vector.
#ifndef EDGE_H
#define EDGE_H

//Edges class in the graph
class edge
{
public:

int node1;
int node2;
int val;

//constructor
edge(int start, int end, int value) :
node1(start),
node2(end),
val(value)
{}

};  //end class edge

#endif```
Code:
```//This is the error I'm getting.
graph.cpp: In member function ‘void graph::sort_edgesArray()’:
graph.cpp:39:33: error: no matching function for call to ‘sort(std::vector<edge>::iterator&, std::vector<edge>::iterator&, <unresolved overloaded function type>)’
/usr/include/c++/4.5/bits/stl_algo.h:5236:18: note: candidate is: void std::sort(_RAIter, _RAIter, _Compare) [with _RAIter = __gnu_cxx::__normal_iterator<edge*, std::vector<edge> >, _Compare = bool (graph::*)(edge&, edge&)]```

2. Make the cmp_val function static or declare it as a non member function.

You also have some const issues. Change cmp_val to take const references.

3. Originally Posted by manasij7479
Make the cmp_val function static or declare it as a non member function.
I'm curious as to why the function needs to be static / non-member. I'm looking at the c++ reference page and the comparison function seems to work fine.

Also curious as to why we need it to be const?

4. The syntax graph::cmp_val is valid for static functions, otherwise member functions have to be called with an object. I'm not sure what you saw on your reference but it's probably not what you think.