Сортировка многопеременной структуры по одной из ее переменных

Доброе утро всем,
Я пытаюсь отсортировать 3 переменные, связанные в структуре на основе значений одной из них. Чтобы прояснить ситуацию, у меня есть структурированный тип переменной с именем edge, и он имеет 3 целых числа: edge.a edge.b и edge.w. Я хочу отсортировать ребра по значениям в файле edge.w. Я узнал, что для этого мне нужно использовать операторы bool, но я еще не выяснил, как это сделать. Это мой код:

struct type{
int a,b,w;
bool operator<(const edge&A) const{
return w<A.w;
};
};
type edge[6];
sort (edge);

Функция sort () включена в библиотеку и выполняет быструю сортировку в массиве в скобках.
Пожалуйста помоги,
TY

1

Решение

Попробуйте следующее

#include <algorithm>

//...

struct type{
int a,b,w;
bool operator<(const type& A) const{
return w<A.w;
};
};

type edge[6];

//...

std::sort( edge, edge + 6 );

Или же

#include <algorithm>
#include <iterator>

//...

struct type{
int a,b,w;
bool operator<(const type& A) const{
return w<A.w;
};
};

type edge[6];

//...

std::sort( std::begin( edge ), std::end( edge ) );

Другой подход заключается в следующем

#include <algorithm>
#include <iterator>

//...

struct type{
int a,b,w;

struct sort_by_a
{
bool operator ()(const type &lhs, const type &rhs ) const
{
return  lhs.a < rhs.a;
}
};
struct sort_by_b
{
bool operator ()(const type &lhs, const type &rhs ) const
{
return  lhs.b < rhs.b;
}
};
struct sort_by_w
{
bool operator ()(const type &lhs, const type &rhs ) const
{
return  lhs.w < rhs.w;
}
};
};

type edge[6];

//...

std::sort( std::begin( edge ), std::end( edge ), type::sort_by_a() );
//...
std::sort( std::begin( edge ), std::end( edge ), type::sort_by_b() );
//...
std::sort( std::begin( edge ), std::end( edge ), type::sort_by_w() );
1

Другие решения


По вопросам рекламы ammmcru@yandex.ru
Adblock
detector