Я предлагаю два решения: первое использование пользовательской структуры с использованием пользовательского оператора <
, который использует std::tie
для сравнения трех целых чисел по порядку, а второе использование std::tuple
.
#include <iostream>
#include <set>
#include <vector>
struct three_integers {
int a, b, c;
bool operator<(const three_integers &other) const {
return std::tie(a, b, c) < std::tie(other.a, other.b, other.c);
}
};
int main(int argc, char *argv[]) {
// 1st solution using a custom structure
// std::set containers are always ordered according to the < operator
std::set<three_integers> sorted_set = {{3, 9, 1}, {1, 5, 2}, {2, 8, 3},
{1, 4, 4}, {1, 6, 5}, {1, 5, 6}};
std::cout << "Sorted set:\n";
for (auto &element : sorted_set) {
std::cout << "(" << element.a << " " << element.b << " " << element.c << ")"
<< std::endl;
}
std::vector<three_integers> sorted_vector = {{3, 9, 1}, {1, 5, 2}, {2, 8, 3},
{1, 4, 4}, {1, 6, 5}, {1, 5, 6}};
// std::vector is not ordered, so we call std::sort on it to make it just like
// std::set, it will use our custom < operator
std::sort(sorted_vector.begin(), sorted_vector.end());
std::cout << "Sorted vector:\n";
for (auto &element : sorted_vector) {
std::cout << "(" << element.a << " " << element.b << " " << element.c << ")"
<< std::endl;
}
// 2nd solution using tuples
std::vector<std::tuple<int, int, int>> sorted_vector_tuple = {
{3, 9, 1}, {1, 5, 2}, {2, 8, 3}, {1, 4, 4}, {1, 6, 5}, {1, 5, 6}};
std::sort(sorted_vector_tuple.begin(), sorted_vector_tuple.end());
std::cout << "Sorted vector of tuples:\n";
for (auto &element : sorted_vector_tuple) {
std::cout << "(" << std::get<0>(element) << " " << std::get<1>(element)
<< " " << std::get<2>(element) << ")" << std::endl;
}
return 0;
}
выход
Sorted set:
(1 4 4)
(1 5 2)
(1 5 6)
(1 6 5)
(2 8 3)
(3 9 1)
Sorted vector:
(1 4 4)
(1 5 2)
(1 5 6)
(1 6 5)
(2 8 3)
(3 9 1)
Sorted vector of tuples:
(1 4 4)
(1 5 2)
(1 5 6)
(1 6 5)
(2 8 3)
(3 9 1)
Я рекомендую вам прочитать документацию std::sort
.