OVH Cloud OVH Cloud

sort by...

3 réponses
Avatar
Aurélien REGAT-BARREL
Bonjour,
J'ai une struct de ce style :

struct toto_t
{
int a;
int b;
fiber_t( int A, int B ) : a( A ), b( B )
{
}
bool operator<( const toto_t & T ) const
{
return this->a < T.a;
}
};

je l'utilise ainsi :

std::vector< toto_t > totos;

// remplissage de totos

std::sort( totos.begin(), totos.end() );

Ca marche, pour trier selon a (normal).
J'aimerais maintenant pouvoir trier selon a ou b.
Quelle est la meilleur façon de faire ?
Merci pour votre aide.

3 réponses

Avatar
Christophe de VIENNE
Aurélien REGAT-BARREL wrote:
Bonjour,


Bonjour,

J'ai une struct de ce style :
[snip]

J'aimerais maintenant pouvoir trier selon a ou b.
Quelle est la meilleur façon de faire ?



Fournir à std::sort une fonction (ou un foncteur) de tri.

Démonstration par l'exemple :

test.cpp
--------
#include <iostream>
#include <vector>
#include <iterator>

struct toto_t
{
int a;
int b;
toto_t( int A, int B ) : a( A ), b( B )
{
}
};

bool CompareA(toto_t const & t1, toto_t const & t2)
{
return t1.a < t2.a;
}

bool CompareB(toto_t const & t1, toto_t const & t2)
{
return t1.b < t2.b;
}

std::ostream & operator<<(std::ostream & o, toto_t const & t)
{
o << "a = " << t.a << ", b = " << t.b << std::endl;
}

int main()
{
std::vector< toto_t > totos;
totos.push_back( toto_t(1, 4) );
totos.push_back( toto_t(2, 3) );
totos.push_back( toto_t(3, 2) );
totos.push_back( toto_t(4, 1) );

std::cout << "Tri selon A" << std::endl;
std::sort( totos.begin(), totos.end(), CompareA );
std::copy( totos.begin(), totos.end(),
std::ostream_iterator<toto_t>(std::cout) );

std::cout << "Tri selon B" << std::endl;
std::sort( totos.begin(), totos.end(), CompareB );
std::copy( totos.begin(), totos.end(),
std::ostream_iterator<toto_t>(std::cout) );
std::cin.ignore();
return 0;
}


Ce qui donne :


:~/prog/test$ g++ test.cpp -o test && ./test
Tri selon A
a = 1, b = 4
a = 2, b = 3
a = 3, b = 2
a = 4, b = 1
Tri selon B
a = 4, b = 1
a = 3, b = 2
a = 2, b = 3
a = 1, b = 4



A+

Christophe

Avatar
Christophe de VIENNE
Petite rectification pour un peu plus de propreté :

Christophe de VIENNE wrote:
[snip]

std::ostream & operator<<(std::ostream & o, toto_t const & t)
{
o << "a = " << t.a << ", b = " << t.b << std::endl;
devient:

o << "a = " << t.a << ", b = " << t.b;
}

[snip]

std::copy( totos.begin(), totos.end(),
std::ostream_iterator<toto_t>(std::cout) );


devient:
std::copy( totos.begin(), totos.end(),
std::ostream_iterator<toto_t>(std::cout, 'n') )

Avatar
Aurélien REGAT-BARREL