スタック上のポップ操作の数をカウントして、C++で配列の各要素を取得します
スタックは降順で埋められ、最初の要素が最も高く、一番上の要素が最も低くなります。
例
入力
Stack [ 7,6,2,1 ] array : 2,1,6,7
出力
Count of number of pop operations on stack to get each element of the array are: 3 1 0 0
説明
Traversing array from 0th index, To get 2 we will pop stack three times. So arr[0] is 3. First two pops will give 7 and 6 also. To get 1 we will pop stack once now. So arr[1] is 1. For 6 and 7 as these are already popped, so arr[2]=arr[3]=0.
入力
Stack [ 3,2,1,1 ] array : 1,2,1,3
出力
Count of number of pop operations on stack to get each element of the array are: 3 0 1 0
説明
Traversing array from 0th index, To get 1 we will pop stack three times. So arr[0] is 3. First two pops will give 3 and 2 also.Traversing array from 0th index, To get 1 we will pop stack three times. So arr[0] is 3. First two pops will give 3 and 2 also.
以下のプログラムで使用されるアプローチは次のとおりです −
このアプローチでは、unordered_map
-
整数配列arr[]を取ります。
-
スタック
stckを使用して、要素を格納します。 -
その中の要素を降順で押します。
-
関数pop_operations(stack
&stck、int arr []、int elements)は、配列の各要素を取得するためのスタック上のポップ操作の数を返します。 -
初期カウントを0とします。
-
unordered_map
umを使用して、スタックでポップ操作を実行しているときに検出された一意の数値を格納します。 -
forループを使用して配列をトラバースします。
-
temp =arr[i]を取ります。
-
温度がumにない場合。取得するために必要な0回のポップ操作を出力します。
-
それ以外の場合、tempが見つからないときに、スタックでpopを実行し、umでポップされた各要素をtrueとして設定し、カウントをインクリメントします。
-
しばらくすると、カウントを印刷します。
-
このようにして、配列の各要素のポップ操作の数を出力します。
例
#include <bits/stdc++.h>
using namespace std;
void pop_operations(stack<int>& stck, int arr[], int elements){
int count = 0;
unordered_map<int, bool> um;
cout<<"Count of number of pop operations on stack to get each element of the array are: ";
for (int i = 0; i < elements; ++i){
int temp = arr[i];
if (um.find(temp) != um.end())
{ cout << "0 "; }
else{
count = 0;
while (stck.top() != temp){
um[stck.top()] = true;
stck.pop();
count++;
}
stck.pop();
count++;
cout<<count<<" ";
}
}
}
int main(){
int elements = 4;
int arr[] = { 2, 1, 6, 7};
stack<int> stck;
stck.push(1);
stck.push(2);
stck.push(6);
stck.push(7);
pop_operations(stck, arr, elements);
return 0;
} 出力
上記のコードを実行すると、次の出力が生成されます-
Count of number of pop operations on stack to get each element of the array are: 3 1 0 0
-
C++の配列内の各要素のSurpasserCountを検索します
1つの配列Aが与えられたと仮定します。その配列内の各要素の超過者の数を見つける必要があります。超過者は、現在の要素の配列の右側に存在するより大きな要素です。 A ={2、7、5、3、0、8、1}とすると、超過者は{4、1、1、1、2、0、0}であるため、2の右側には4つの数字があります。 4よりも多く、他の人にも同じルールがあります。解決策は非常に単純で、2つのネストされたループがあり、要素ごとに、超過者をカウントして、別の配列に格納します。 例 #include <iostream> using namespace std; void gerSurpassers(int arr[
-
C ++ STLの配列get()関数?
このセクションでは、C ++ STLの配列のget()関数について説明します。この関数は、配列コンテナのi番目の要素を取得するために使用されます。構文は次のようになります- 構文 get<i> array_name この関数は2つの必須パラメーターを取ります。はインデックスパラメータです。配列のi番目の位置を指すために使用されます。 2番目の引数はarray_nameです。これは、このi番目の要素から取得される実際の配列です。この関数はi番目の要素を返します。 アイデアを得るための1つの例を見てみましょう。 例 #include<iostream> #include