C / C ++で日付の配列をソートする方法は?
日付の配列があるとします。ここでは、CまたはC++コードを使用してソートする方法を説明します。日付はクラスに格納されます(構造体はCでも使用できます)。 C++STLのソート機能を使用します。日付を比較するには、sort関数で使用される独自のcompare関数を作成する必要があります。より良いビューを得るために例を見てみましょう。
例
#include<iostream>
#include<iostream>
#include<algorithm>
using namespace std;
class Date {
public:
int d, m, y;
};
bool compare(const Date &date1, const Date &date2){
if (date1.y < date2.y)
return true;
if (date1.y == date2.y && date1.m < date2.m)
return true;
if (date1.y == date2.y && date1.m == date2.m && date1.d < date2.d)
return true;
return false;
}
void sortDateArray(Date arr[], int n) {
sort(arr, arr+n, compare);
}
int main() {
Date arr[] = {{20, 1, 2017},
{25, 3, 2010},
{ 3, 12, 1956},
{18, 10, 1982},
{19, 4, 2011},
{ 9, 7, 2013}};
int n = sizeof(arr)/sizeof(arr[0]);
sortDateArray(arr, n);
cout << "Sorted dates are" << endl;
for (int i=0; i<n; i++) {
cout << arr[i].d << " " << arr[i].m << " " << arr[i].y << endl;
}
} 出力
Sorted dates are 3 12 1956 18 10 1982 25 3 2010 19 4 2011 9 7 2013 20 1 2017
-
Androidで配列要素を並べ替える方法は?
この例は、Androidで配列要素を並べ替える方法を示しています。 ステップ1 − Android Studioで新しいプロジェクトを作成し、[ファイル]⇒[新しいプロジェクト]に移動して、新しいプロジェクトを作成するために必要なすべての詳細を入力します。 ステップ2 −次のコードをres / layout/activity_main.xmlに追加します。 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.a
-
C /C++での多次元配列の初期化
多次元配列では、配列の次元は1より大きい必要があります。次の図は、次元が3 x 3x3の多次元配列のメモリ割り当て戦略を示しています。 これは、多次元配列を初期化するためのC++プログラムです。 アルゴリズム Begin Initialize the elements of a multidimensional array. Print the size of the array. Display the content of the array. End 例 #include<iostream>