I’ve been trying every tip provided on this site, but none worked, so I’m going to explain what my issue is.
I’m tyring to sort a vector containing pointers to objects, so of couse I can’t use the std::sort(vector.begin(), vector.end()) syntax because it would use the “<” operator on pointers. Here is a sample of my code :
// Vertex.h
class Vertex
{
public :
inline int getPond() const {return m_Pond;}
private :
int m_Pond;
}
.
//Graph.h
class Graph
{
public :
void sortVertexPond(vector<Vertex*> VertexVect);
inline bool compareVertex(const Vertex* LeftVertex, const Vertex* RightVertex){return (LeftVertex->getPond() < RightVertex->getPond());}
void testFunct ();
private :
vector<vector Vertex*>> m_VertexByLayers;
}
.
//Graph.cpp
#include <algorithm>
void Graph::sortVertexPond(vector<Vertex*> VertexVect)
{
std::sort(VertexVect.begin(), VertexVect.end(), compareVertex);
//std::sort(VertexVect.begin(), VertexVect.end(), compareVertexStruct());
}
/*struct compareVertexStruct {
bool operator ()(Vertex* LeftVertex, Vertex* RightVertex) {return (LeftVertex->getPond() < RightVertex->getPond()); }
};*/
void testFunct()
{
this->sortVertexPond(m_VertexByLayers.at(0));
}
This won’t compile as I get the following error :
error C2780: 'void std::sort(_RanIt,_RanIt)' : 2 arguments expected - 3 provided
As you can see in the code I provided, I already tried to do it by creating a Functor. This way I add no issues compiling and running, the odd thing is that even if my functor was called (which I could see by adding a cout inside my operator), std::sort didn’t sort anything.
I had this kind of results :
Input : [3,2,1]
3<2? 0
2<1? 0
Output : [3,2,1]
Input : [1,2,3]
1<2? 1
2<3? 1
Output : [1,2,3]
Could please anyone help me fix this?
PS : Sorry for my english, it isn’t my home language.
Edit : Thanks to all of you. Here’s what I did to fix it.
//Graph.h
class Graph
{
public :
vector<Vertex*> sortVertexPond(vector<Vertex*> VertexVect);
}
//Graph.cpp
#include <algorithm>
struct compareVertexStruct {bool operator ()(Vertex* LeftVertex, Vertex* RightVertex) {return (LeftVertex->getPond() < RightVertex->getPond());}};
vector<Vertex*> Graph::sortVertexPond(vector<Vertex*> VertexVect)
{
std::sort(VertexVect.begin(), VertexVect.end(), compareVertexStruct());
return VertexVect;
}
You are passing your vertex vector by value to sortVertexPond:
Thus, you are making a copy when calling that function, and then sorting the copy, but the original is not changed.
Try passing the vector by reference: