前提条件: C++ の std::sort 、 C++ のベクトル 、 C++ でベクトルを初期化する 。
CPP
// C++ program to sort a vector in non-decreasing> // order.> #include> using> namespace> std;> > int> main()> {> > vector<> int> >v{ 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 };>> > > sort(v.begin(), v.end());> > > cout <<> 'Sorted
'> ;> > for> (> auto> x : v)> > cout << x <<> ' '> ;> > > return> 0;> }> |
>
>出力
Sorted 0 1 2 3 4 5 6 7 8 9>
降順に並べ替えるにはどうすればよいですか?
sort() は、要素を並べ替える順序を指定するために使用される 3 番目のパラメーターを取ります。 great() 関数を渡すと、降順で並べ替えることができます。この関数は、より大きな要素を前に置く方法で比較を行います。
CPP
// C++ program to sort a vector in non-increasing> // order.> #include> using> namespace> std;> > int> main()> {> > vector<> int> >v{ 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 };>> > > sort(v.begin(), v.end(), greater<> int> >());>> > > cout <<> 'Sorted
'> ;> > for> (> auto> x : v)> > cout << x <<> ' '> ;> > > return> 0;> }> |
>
>出力
Sorted 9 8 7 6 5 4 3 2 1 0>
で並べ替える方法 特定の順序ですか?
独自のコンパレーター関数を作成し、それを 3 番目のパラメーターとして渡すこともできます。
文字列から整数へのJava
コンパレータ関数は、返されたステートメントが true か false かをチェックし、sort 関数に渡される bool 値を返します。
たとえば、間隔 i1 = { 6 , 8 } および間隔 i2 = { 1, 9 } とします。これをコンパレータ関数に渡すと、比較が行われます。 i1.スタート そして i2.スタート 。以降、i1.start (=6)
CPP
// A C++ program to sort vector using> // our own comparator> #include> using> namespace> std;> > // An interval has start time and end time> struct> Interval {> > int> start, end;> };> > // Compares two intervals according to starting times.> bool> compareInterval(Interval i1, Interval i2)> {> > return> (i1.start } int main() { vector v { { 6, 8 }, { 1, 9 }, { 2, 4 }, { 4, 7 } }; // sort the intervals in increasing order of // start time sort(v.begin(), v.end(), compareInterval); cout << 'Intervals sorted by start time :
'; for (auto x : v) cout << '[' << x.start << ', ' << x.end << '] '; return 0; }> |
>
>出力
Intervals sorted by start time : [1, 9] [2, 4] [4, 7] [6, 8]>
コンパレーター関数を使用して、パラメーターに基づいて配列を降順に並べ替えるにはどうすればよいですか?
コンパレータ関数は、配列内の要素が降順で並べ替えられるような方法で渡すことができます。
C++
// A C++ program to sort vector using> // our own comparator> #include> using> namespace> std;> > // An interval has start time and end time> struct> Interval {> > int> start, end;> };> > // Compares two intervals according to ending times in descending order.> bool> compareInterval(Interval i1, Interval i2)> {> > return> (i1.end>i2.終了);>> }> > int> main()> {> > vector v { { 6, 8 }, { 1, 9 }, { 2, 4 }, { 4, 7 } };> > > // sort the intervals in decreasing order of> > // end time> > sort(v.begin(), v.end(), compareInterval);> > > cout <<> 'Intervals sorted by ending time in descending order :
'> ;> > for> (> auto> x : v)> > cout <<> '['> << x.start <<> ', '> << x.end <<> '] '> ;> > > return> 0;> }> |
>
>出力
Intervals sorted by ending time in descending order : [1, 9] [6, 8] [4, 7] [2, 4]>
関連記事 :
ペアのベクトルを並べ替える |セット1
ペアのベクトルを並べ替える |セット2