1

I have a struct with three int in it.

struct x{
int a,
    b,
    c;
};

I am using the struct to store triplets in the vector as the triplets will represent source, destination and weight.

vector<x> myVec;

and I am adding values in it with myVec.push_back({a, b, c});

So far so good, but I want to sort them according to their weights, that'd be c variable. I am unsure how to use std::sort on my vector.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
vhmvd
  • 192
  • 3
  • 15

1 Answers1

3

You can use a lambda expression as for example

#include <vector>
#include <iterator>
#include <algorithm>

// ...

std::sort( std::begin( myVec ), std::end( myVec ),
           []( const auto &a, const auto &b )
           {
               return a.c < b.c;
           } ); 

You can define the lambda expression object directly in the call of std::sort as it has been shown above or separately as it is shown in the demonstrative program below

#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>

struct x{
int a,
    b,
    c;
};

int main() 
{
    std::vector<x> myVec =
    {
        { 2, 2, 2 }, { 1, 1, 1 }, { 3, 3, 3 }
    };
    
    for ( const auto &item : myVec )
    {
        std::cout << item.a << ' ' << item.b << ' ' << item.c << '\n';
    }
    std::cout << '\n';
    
    auto compare_by_weight = []( const auto &a, const auto &b )
    {
        return a.c < b.c;
    };
    
    std::sort( std::begin( myVec ), std::end( myVec ), compare_by_weight );
    
    for ( const auto &item : myVec )
    {
        std::cout << item.a << ' ' << item.b << ' ' << item.c << '\n';
    }
    std::cout << '\n';
    
    return 0;
}

The program output is

2 2 2
1 1 1
3 3 3

1 1 1
2 2 2
3 3 3

Another approach is to define a function object. For example.

#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>

struct x{
int a,
    b,
    c;
};

struct compare_by_weight
{
    bool operator ()( const x &a, const x &b ) const
    {
        return a.c < b.c;
    }
};

int main() 
{
    std::vector<x> myVec =
    {
        { 2, 2, 2 }, { 1, 1, 1 }, { 3, 3, 3 }
    };
    
    for ( const auto &item : myVec )
    {
        std::cout << item.a << ' ' << item.b << ' ' << item.c << '\n';
    }
    std::cout << '\n';
    
    std::sort( std::begin( myVec ), std::end( myVec ), compare_by_weight() );
    
    for ( const auto &item : myVec )
    {
        std::cout << item.a << ' ' << item.b << ' ' << item.c << '\n';
    }
    std::cout << '\n';
    
    return 0;
}

The program output is

2 2 2
1 1 1
3 3 3

1 1 1
2 2 2
3 3 3
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335