C++STLを使用してソートされた配列の床と天井を見つける
このチュートリアルでは、C++STLを使用してソートされた配列の床と天井を見つけるプログラムについて説明します。
ソートされた配列の床と天井を見つけるために、STLのlower_bound()関数とupper_bound()関数をそれぞれ使用します。
例
#include <bits/stdc++.h>
using namespace std;
//finding floor of given array
void printFloor(int arr[], int n1,
int findFloor[], int n2){
int low;
cout << "Floor : ";
for (int i = 0; i < n2; i++) {
low = (lower_bound(arr, arr + n1, findFloor[i]) - arr);
if (arr[low] > findFloor[i])
cout << arr[low - 1] << " ";
else
cout << arr[low] << " ";
}
cout << endl;
}
//fincding ceil of given array
void printCeil(int arr[], int n1,
int findCeil[], int n2){
int up;
cout << "Ceil : ";
for (int i = 0; i < n2; i++) {
up = (upper_bound(arr, arr + n1, findCeil[i]) - arr);
if (arr[up] > findCeil[i] && arr[up - 1] == findCeil[i]) {
cout << arr[up - 1] << " ";
}
else
cout << arr[up] << " ";
}
cout << endl;
}
int main(){
int arr[] = { 1, 2, 4, 7, 11, 12, 23, 30, 32 };
int n1 = sizeof(arr) / sizeof(arr[0]);
cout << "Original Array: ";
for (unsigned int i = 0; i < n1; i++)
cout << " " << arr[i];
cout << "\n";
int find[] = { 1, 3, 5, 7, 20, 24 };
int n2 = sizeof(find) / sizeof(find[0]);
cout << "Values: ";
for (unsigned int i = 0; i < n2; i++)
cout << find[i] << " ";
cout << "\n";
printFloor(arr, n1, find, n2);
printCeil(arr, n1, find, n2);
return 0;
} 出力
Original Array: 1 2 4 7 11 12 23 30 32 Values: 1 3 5 7 20 24 Floor : 1 2 4 7 12 23 Ceil : 1 4 7 7 23 30
-
STLを使用したC++の配列製品
これは、配列製品を見つけるためのC++プログラムの例です。 アルゴリズム Begin Initialize the values of array. Call used defined function accumulate to return the product of array. Print the solution. End. サンプルコード #include <iostream> #include <numeric> using namespace std; int ProductOfArray(int p[], int n) { &nbs
-
C++の天井関数と床関数
天井関数 ceil関数は、その値以上の可能な限り最小の整数値を返します。この関数は、C++言語の「cmath」ヘッダーファイルで宣言されています。セル値が計算されるのは単一の値です。変数のデータ型は、double / float /longdoubleのみである必要があります。 これがC++言語でのceil関数の構文です double ceil(double x); float ceil(float x); これがC++言語のceil関数の例です 例 #include <iostream> #include <cmath> using namespace std;