How to sort a Struct by a member data

Started by
1 comment, last by DividedByZero 1 year, 6 months ago

Hi Guys,

I'm trying to figure out how I would sort a struct by a member value.

In this case I have 3 points of a triangle and I want to sort them from lowest to highest given their y position.

I have gotten as far as the code below but it gives me Error C2672 'operator __surrogate_func': no matching overloaded function found.

I know the code isn't quite right but I'm not too sure where to go from here.

Any help would be greatly appreciated.

#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <functional>
#include <array>
#include <iostream>
#include <string_view>

struct POINT
{
	int x, y;
};

struct TRIANGLE
{
	POINT a, b, c;
};


int main()
{
	TRIANGLE tri;
	tri.a = POINT{ 160, 125 };
	tri.b = POINT{ 260, 100 };
	tri.c = POINT{ 60, 175 };


	std::array<TRIANGLE, 3> s = { tri.a.y, tri.b.y, tri.c.y };
	std::sort(s.begin(), s.end());

}
Advertisement

I believe I have worked it out. Posting the solution here so future self can thank past self, when I go to do the same thing in a few years time. :D

#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <functional>
#include <array>
#include <iostream>
#include <string_view>

struct POINT
{
	int x, y;
};

struct SortFunctor
{
	bool operator() (const POINT& op0, const POINT& op1) const
	{
		return op0.y < op1.y;
	}
};


int main()
{
	POINT p[3];
	p[0] = POINT{ 160, 125 };
	p[1] = POINT{ 260, 100 };
	p[2] = POINT{ 60, 175 };
	
	std::array<POINT, 3> s = { p[0], p[1], p[2] };
	std::sort(s.begin(), s.end(),SortFunctor());

	std::cout << s[0].x << "\t" << s[0].y << "\r\n";
	std::cout << s[1].x << "\t" << s[1].y << "\r\n";
	std::cout << s[2].x << "\t" << s[2].y << "\r\n";
	
	system("PAUSE");
}

This topic is closed to new replies.

Advertisement